![](/img/trans.png)
[英]How do you update a label every time text is typed into a textbox, using tkinter
[英]How do I update a variable by grabbing text from a textbox in tkinter using the enter key?
我正在使用 Tkinter 並嘗試創建一個聊天程序。 我將其設置為打開一個新的 window,提示您輸入您希望連接的用戶的 IP。 當您按下回車鍵時,它應該將變量更新為該 IP 地址以供以后使用。 問題是變量沒有更新,而是保持其初始值。 我正在使用.get()
function 從文本框中獲取文本。 當我打印.get()
function 時,它可以工作,但使用.get()
設置變量不起作用。 發送仍在打印 1. 有什么想法嗎?
other_address = 1
def join():
newWindow = Toplevel(master)
newWindow.title("IP")
newWindow.geometry("300x50")
directions = Label(newWindow, text="Enter the IP Address of the user you would like to join")
directions.pack()
enter_hostname = Entry(newWindow)
enter_hostname.pack()
newWindow.bind("<Return>", lambda x: other_address == enter_hostname.get())
newWindow.bind("<Return>", lambda x: print(enter_hostname.get()))
def send():
print (other_address)
這是對評論中給出的 SyntaxError 的答案:這里的問題是 lambda 表達式創建了一個“范圍”,這意味着當它結束時它創建的任何變量都會自動銷毀。 對此的解決方案是創建一個適當的 function 將other_address
放入其全局 scope 以便它可以像這樣正確編輯它:
def set_address(x):
global other_address
other_address = enter_hostname.get()
那么綁定可以是:
newWindow.bind("<Return>", set_address)
您只需將 set_address function 傳遞給它,而不是 lambda 表達式
我正在使用 Tkinter 並嘗試創建一個聊天程序。 我將其設置為打開一個新的 window,提示您輸入您希望連接的用戶的 IP。 當您按下回車鍵時,它應該將變量更新為該 IP 地址以供以后使用。 問題是變量沒有更新,而是保持其初始值。 我正在使用.get()
function 從文本框中獲取文本。 當我打印.get()
function 時,它可以工作,但使用.get()
設置變量不起作用。 發送仍在打印 1. 有什么想法嗎?
other_address = 1
def join():
newWindow = Toplevel(master)
newWindow.title("IP")
newWindow.geometry("300x50")
directions = Label(newWindow, text="Enter the IP Address of the user you would like to join")
directions.pack()
enter_hostname = Entry(newWindow)
enter_hostname.pack()
newWindow.bind("<Return>", lambda x: other_address == enter_hostname.get())
newWindow.bind("<Return>", lambda x: print(enter_hostname.get()))
def send():
print (other_address)
雙等號運算符==
不會在 python 中創建變量,而是所謂的等號運算符,因此它檢查它們是否相等並返回 True 或 False。 要在 python 中設置變量,您需要使用單個等號=
以便該行變為: newWindow.bind("<Return>", lambda x: other_address = enter_hostname.get())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.