单击时从 tkinter 按钮获取返回值 [英] Getting return value from tkinter button when clicked

查看:62
本文介绍了单击时从 tkinter 按钮获取返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 tkinter 按钮来为变量赋值,但我不知道怎么做.我不能只是将分配放在按钮回调函数中,因为它在回调函数中是本地的,并且会丢失.如何从主函数中的按钮取回值?

I need a tkinter Button to assign a value to a variable, but I can't figure out how. I can't just put the assignment in the button callback function, because that would be local within the callback function and would be lost. How can I get a value back from the button in my main function?

代码如下:

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() 的返回中检索当前.

Also, I need to be able to retrieve current from the return of newfile().

推荐答案

如果你使用nonlocal current,你应该可以直接在create_file中设置当前变量函数,只要已经定义了 current ,它就应该可以工作.请记住将连接到按钮 command 参数的函数调用放在 lambda 函数中,以便您可以为其提供参数.不过,在未来,确实要遵循注释,整个代码可以重新组织,使其看起来更合理......

If you use nonlocal current, you should be able to directly set the current variable within the create_file function, as long as current has already been defined, it should work. Remember to put the function call connected to the buttons command argument, in a lambda function, so you can give it the argument. In the future, though, really do follow the comments, the whole code could be reorganised to make it seem more sensible...

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

这篇关于单击时从 tkinter 按钮获取返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆