gpt4 book ai didi

python - Tkinter。在输入框中按 Enter。附加到文本框。如何?

转载 作者:行者123 更新时间:2023-11-28 21:56:11 25 4
gpt4 key购买 nike

我正在制作一个聊天程序,并决定使用 Tkinter 作为界面。

我想做的是用 C# 做的轻而易举,但 Tkinter 对我来说是新手。

基本上我有一个带有 Entry 控件和 Text 控件的窗体。

我想知道如何在用户按下 Enter 后将文本从 Entry 控件追加到 Text 控件。

到目前为止,这是我的代码:

from tkinter import *

class Application:

def hello(self):
msg = tkinter.messagebox.askquestion('title','question')

def __init__(self, form):
form.resizable(0,0)
form.minsize(200, 200)
form.title('Top Level')

# Global Padding pady and padx
pad_x = 5
pad_y = 5

# create a toplevel menu
menubar = Menu(form)
#command= parameter missing.
menubar.add_command(label="Menu1")
#command= parameter missing.
menubar.add_command(label="Menu2")
#command= parameter missing.
menubar.add_command(label="Menu3")

# display the menu
form.config(menu=menubar)

# Create controls

label1 = Label(form, text="Label1")
textbox1 = Entry(form)
#command= parameter missing.
button1 = Button(form, text='Button1')

scrollbar1 = Scrollbar(form)
textarea1 = Text(form, width=20, height=10)

textarea1.config(yscrollcommand=scrollbar1.set)
scrollbar1.config(command=textarea1.yview)

textarea1.grid(row=0, column=1, padx=pad_x, pady=pad_y, sticky=W)
scrollbar1.grid(row=0, column=2, padx=pad_x, pady=pad_y, sticky=W)
textbox1.grid(row=1, column=1, padx=pad_x, pady=pad_y, sticky=W)
button1.grid(row=1, column=2, padx=pad_x, pady=pad_y, sticky=W)

form.mainloop()

root = Tk()
Application(root)

最佳答案

因此您使用的是 tkinter.Text 框,它支持 .insert 方法。让我们使用它吧!

def __init__(self,form):

# Lots of your code is duplicated here, so I'm just highlighting the main parts

button1 = Button(form, text='Button1', command = self.addchat)
self.textbox = textbox1 # to make it accessible outside your __init__
self.textarea = textarea1 # see above

form.bind("<Return>", lambda x: self.addchat())
# this is the magic that makes your enter key do something

def addchat(self):
txt = self.textbox.get()
# gets everything in your textbox
self.textarea.insert(END,"\n"+txt)
# tosses txt into textarea on a new line after the end
self.textbox.delete(0,END) # deletes your textbox text

关于python - Tkinter。在输入框中按 Enter。附加到文本框。如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21894947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com