我正在构建一个聊天GUI。按回车键,我希望文本字段显示在文本框中,并保存在文件中。我不想使用单独的按钮。它正确显示在文本框中,但未保存在文件中。请告诉我怎么做。这是我第一次使用tkinter。
from Tkinter import *
root = Tk()
frame = Frame(root, width=300, height=1000)
frame.pack(side=BOTTOM)
#username entry
L1 = Label(frame, text="User Name")
L1.pack(side = LEFT)
input_username = StringVar()
input_field1 = Entry(frame, text=input_username, width=10)
input_field1.pack(side=LEFT, fill=X)
#addresee entry
L2 = Label(frame, text="@")
L2.pack(side = LEFT)
input_addresee = StringVar()
input_field2 = Entry(frame, text=input_addresee, width=10)
input_field2.pack(side=LEFT, fill=X)
#user comment entry
L3 = Label(frame, text="Comment")
L3.pack(side = LEFT)
input_usertext = StringVar()
input_field3 = Entry(frame, text=input_usertext, width=100)
input_field3.pack(side=LEFT, fill=X)
#write to a file
def save():
text = input_field1.get() + input_field2.get() + input_field3.get()
with open("test.txt", "w") as f:
f.write(text)
#chat box
chats = Text(root)
chats.pack()
def Enter_pressed(event):
input_get_name = input_field1.get()
print(input_get_name)
chats.insert(INSERT, '%s : ' % input_get_name)
input_username.set('')
input_get_add = input_field2.get()
print(input_get_add)
chats.insert(INSERT, '@%s : ' % input_get_add)
input_addresee.set('')
input_get_comment = input_field3.get()
print(input_get_comment)
chats.insert(INSERT, '%s\n' % input_get_comment)
input_usertext.set('')
save()
frame2 = Frame(root)
L2_1 = Label(frame2, text="All chats")
L2_1.pack(side = TOP)
input_field1.bind(Enter_pressed)
input_field2.bind(Enter_pressed)
input_field3.bind("<Return>", Enter_pressed)
frame2.pack()
root.mainloop()
答案 0 :(得分:1)
正如您所说,您将输入字段设置为空白
以下是解决方案:
def save(text):
with open("test.txt", "w") as f:
f.write(text)
在致电保存时:
save(input_get_name+": "+input_get_add+": "+input_get_comment)