![](/img/trans.png)
[英]how to make an entry box that moves to another window if what is entered is equal to what is in a text file in Tkinter
[英]how to pass the text entered in entry box in tkinter from one function to another?
我想將輸入框文本從一個函數傳遞到另一個函數,但它給了我未定義變量本身的錯誤。這是我的代碼。
from Tkinter import *
def mhello():
mtext=ment.get()
print mtext
def main():
root=Tk()
ment=StringVar()
root.title('Test')
mlabel=Label(root,text='Enter Text').pack()
mentry=Entry(root,textvariable=ment).pack()
mbutton=Button(root,text='Click Me',command=mhello).pack()
if __name__ == '__main__':
main()
它給出的錯誤為:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__
return self.func(*args)
File "pygui.py", line 3, in mhello
mtext=ment.get()
NameError: global name 'ment' is not defined
首先,您有一個變量作用域問題,函數中定義的變量是這些函數的本地變量,因此ment
是在main
定義的,而不是在mhello
中mhello
。 要么將變量傳遞給mhello
要么使ment
成為一個全局變量。 所以我們可以像這樣傳入變量:
def mhello(var):
mtext=var.get()
print(mtext)
然后我們需要從我們的按鈕調用它:
mbutton=Button(root, text='Click Me', command=lambda: mhello(ment)).pack()
我們需要實際調用主mainloop
以使代碼正常運行:
root.mainloop()
沒有它,就不會運行 GUI。
在設計層面,我通常創建類來存儲 GUI 相同部分中的變量,以避免需要傳遞大量參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.