[英]Tkinter How to create new instance of chat window whenever the button is clicked
[英]How to create a chat window with tkinter?
我試圖創建一個聊天窗口,但它無法正常工作。 每次輸入消息時,都會彈出並增加窗口。 我該怎么辦?
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()
每次按Enter鍵時,您要添加標簽,請嘗試在“ 文本”小部件中顯示消息:
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()
您的問題是您創建的標簽將window
作為父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的觀點,則應使用文本小部件。
嘗試使用更簡單的方法(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年級計算機科學專業的學生,所以要謙虛一些,但是我希望這可以解決您的問題:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.