使用 Tkinter 包创建 GUI 后无法打印值名称

Unable to print value name after creating GUI using Tkinter package

我写了一个代码来弹出一个框来使用 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)