如何保存变量"name"以备将来使用?我想稍后在代码中调用这个变量,但由于某种原因,我得到了这个错误:;NameError:名称"name"未定义">
from tkinter import *
OPTIONS = [
"Name 1",
"Name 2",
"Name 3"
]
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
name =variable.get()
print (name)
master.destroy()
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
你是说"以备将来使用";在同一模块中?如果是,您只需要将其作为全局变量,如:
def ok():
global name
name = variable.get()