点击后从tkinter按钮获取返回值
我需要一个tkinter按钮来为变量赋值,但我不知道如何。我不能只将该赋值放在按钮回调函数中,因为这将在本地回调函数中丢失。如何从主函数中的按钮获取值?点击后从tkinter按钮获取返回值
下面是代码:
def newfile():
def create_file(entry):
file=open(entry.get(0),'w')
return file
chdir(askdirectory())
name=Tk()
name.title("Name the File?")
prompt=Label(name, text="Enter name for new file:")
prompt.grid(row=0)
e=Entry(name)
e.grid(row=1)
e.insert(0, "Untitled")
create=Button(name, text="Create")
#Code I want the button to execute: current=create_file(e), name.destroy()
create.grid(row=2, column=3)
name.mainloop()
return current
有谁知道?
此外,我需要能够从newfile()
返回检索当前。
如果你使用nonlocal current
,你应该能够直接在create_file
函数中设置当前变量,只要电流已经被定义了,它就可以工作。请记住将函数调用连接到按钮command
参数,并将其放入一个lambda函数中,以便您可以给它参数。在未来,虽然真的遵循了评论,整个代码可以重组,使其看起来更明智...
def newfile():
current = None
def create_file(entry):
nonlocal current
current = open(entry.get(),'w')
e.master.destroy()
chdir(askdirectory())
name=Tk()
name.title("Name the File?")
prompt=Label(name, text="Enter name for new file:")
prompt.grid(row=0)
e=Entry(name)
e.grid(row=1)
e.insert(0, "Untitled")
create=Button(name, text="Create", command = lambda: create_file(e))
create.grid(row=2, column=3)
name.mainloop()
return current
我想我已经明白了。 – 2015-04-05 17:38:37
但是,如何从'newfile()'中获取当前值?它也必须进入一个按钮,我需要消除它。 – 2015-04-10 16:03:44
'current'返回,只是存储: 'file = newfile()' – Annonymous 2015-04-10 18:40:45
我会做的是创建一个类,在这个类中定义名称和当前作为类变量(self.name和self.current),所以我可以在没有问题的类函数中修改它们。
你是什么意思?你能提供一些代码吗? – 2015-04-05 17:13:30
请问您能提供一些代码吗?没有它,很难看出你的问题是什么。 – 2015-04-03 13:42:49
它就在那里。上下文是我正在创建一个文本编辑器。 – 2015-04-04 01:02:52
您似乎确实有两个问题:将数据('e')发送到您的回调函数中,并从中获取返回值('file')。按钮回调函数的API似乎不允许任何一个。 – 2015-04-04 11:54:23