繁体   English   中英

如何将在 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定义的,而不是在mhellomhello 要么将变量传递给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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM