如何解决使用 Tkinter 包创建 GUI 后无法打印值名称
我写了一个代码来弹出一个框来输入使用 Tkinter 的值。在 mainloop() 之后,当我尝试打印我在框中给出的值时,它抛出错误。代码如下
from tkinter import *
root = Tk()
root.geometry("400x300")
nameLabel = Label(root,text="Please Enter Table Name or Table ID")
ent = Entry(root,bd=5)
def getName():
#print("Table Name is : ",ent.get())
table = ent.get()
print(table)
root.destroy()
submit = Button(root,text ="Submit",command = getName)
nameLabel.pack()
ent.pack()
submit.pack(side = BOTTOM)
root.mainloop()
table1 = table
print(table)
给出的错误是:
Traceback (most recent call last):
File "input_table_name.py",line 22,in <module>
table1 = table
NameError: name 'table' is not defined
解决方法
您在函数内部创建变量 table
,这意味着它是本地的,不能在外部使用。您可以使用 global
关键字使变量成为全局变量。
from tkinter import *
root = Tk()
root.geometry("400x300")
nameLabel = Label(root,text="Please Enter Table Name or Table ID")
ent = Entry(root,bd=5)
def getName():
#print("Table Name is : ",ent.get())
global table
table = ent.get()
print(table)
root.destroy()
submit = Button(root,text ="Submit",command = getName)
nameLabel.pack()
ent.pack()
submit.pack(side = BOTTOM)
root.mainloop()
table1 = table
print(table)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。