Python 保存tkinter字符串以在mainloop之后使用

Python 保存tkinter字符串以在mainloop之后使用,python,tkinter,Python,Tkinter,我试图让我的脚本运行,然后在mainloop结束后保存一个userinput字符串,因为我想稍后在同一个python脚本中调用它(但不是在tkinter中)。 我要保存的字符串是位置(w)和mac。 请看下面的脚本,让我知道如果你有任何想法 from Tkinter import * OPTIONS = [ "Choose Site", "Site1", "Site2", "Site3", ] master = Tk() variable = StringVar(master) var

我试图让我的脚本运行,然后在mainloop结束后保存一个userinput字符串,因为我想稍后在同一个python脚本中调用它(但不是在tkinter中)。 我要保存的字符串是位置(w)和mac。 请看下面的脚本,让我知道如果你有任何想法

from Tkinter import *

OPTIONS = [
"Choose Site",
"Site1",
"Site2",
"Site3",
] 


master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mac= Entry (master, text= "Enter Mac Address")
mac.pack()


def call_and_ok():
    print ("Location:" + variable.get())
    print ("MAC address is:" + mac.get())

button_1 = Button(master, text="RUN", command=call_and_ok,)
button_1.pack()


mainloop()


location = variable.get()
macstored = mac.get()

print (location)
通过使用
master.protocol(“WM\u DELETE\u window”,callback)
,您可以使用Tkinter定义自己的窗口删除处理程序。在这个处理程序中,您可以确保在实际销毁mainloop之前获取当前值并存储它们(在全局变量中)

在调用
mainloop()


那很好用。谢谢你的快速回答!没问题。请记住,在销毁窗口时保存小部件的内容对于用户来说可能不是最直观的。您可以考虑在“代码>回调< /代码>中添加行到按钮后面的命令,这样按下按钮就可以保存条目并销毁窗口。查看一下,这是草稿的草稿,但我想工作的函数现在至少工作了:”
location = ''
macstored = ''

def callback():
    global location
    global macstored
    location = variable.get()
    macstored = mac.get()
    master.destroy()

master.protocol("WM_DELETE_WINDOW", callback)