我尝试创建一个聊天窗口但它无法正常工作。每次我输入消息时,它都会弹出并增加窗口。我该怎么办?
from Tkinter import *
window = Tk()
input_user = StringVar()
input_field = Entry(window, text=input_user)
input_field.pack(side=BOTTOM, fill=X)
def Enter_pressed(event):
input_get = input_field.get()
print(input_get)
label = Label(window, text=input_get)
input_user.set('')
label.pack()
return "break"
frame = Frame(window, width=300, height=300)
input_field.bind("<Return>", Enter_pressed)
frame.pack()
window.mainloop()
答案 0 :(得分:2)
每次按Enter键时都会添加标签,尝试在Prefetch()-object小部件中显示消息:
from Tkinter import *
window = Tk()
messages = Text(window)
messages.pack()
input_user = StringVar()
input_field = Entry(window, text=input_user)
input_field.pack(side=BOTTOM, fill=X)
def Enter_pressed(event):
input_get = input_field.get()
print(input_get)
messages.insert(INSERT, '%s\n' % input_get)
# label = Label(window, text=input_get)
input_user.set('')
# label.pack()
return "break"
frame = Frame(window) # , width=300, height=300)
input_field.bind("<Return>", Enter_pressed)
frame.pack()
window.mainloop()
答案 1 :(得分:2)
您的问题是,您创建的标签以window
为父级而不是frame
,因此它们打包在frame
下方,而不在内部:
from Tkinter import *
window = Tk()
input_user = StringVar()
input_field = Entry(window, text=input_user)
input_field.pack(side=BOTTOM, fill=X)
def enter_pressed(event):
input_get = input_field.get()
print(input_get)
label = Label(frame, text=input_get)
input_user.set('')
label.pack()
return "break"
frame = Frame(window, width=300, height=300)
frame.pack_propagate(False) # prevent frame to resize to the labels size
input_field.bind("<Return>", enter_pressed)
frame.pack()
window.mainloop()
但是如果你想能够滚动你的消息,我同意Steven Summers和WaIR,你应该使用Text小部件。
答案 2 :(得分:0)
尝试使用更简单的方法(Python 3.7.3)
from tkinter import *
root = Tk()
root.resizable(height = False, width = False)
root.title('Chat Window Thingy')
l1 = Label(root, text = 'Your Text Here',fg='green').pack()
e1 = Entry(root, text = 'Your text here').pack()
root.mainloop()
我是10年级计算机科学系的学生,所以要保持谦虚,但我希望这可以解决您的问题:)