简体   繁体   English

Python TkInter按钮命令返回

[英]Python TkInter Button Command Return

I'm having trouble returning a variable from a TkInter button command. 我无法从TkInter按钮命令返回变量。 This here is my code: 这是我的代码:

class trip_calculator:

    def gui(self):

        returned_values = {} 

        def open_file_dialog():
            returned_values['filename'] = askopenfilename()

        root = Tk()
        Button(root, text='Browse', command= open_file_dialog).pack()

        filepath = returned_values.get('filename')

        root.mainloop()

        return filepath

        root.quit()

I just want to return the filepath of a TXT file. 我只想返回TXT文件的文件路径。 The TkInter window is open and I can browse and choose the file but it then doesn't return the path. TkInter窗口打开,我可以浏览并选择文件,但是它不返回路径。 I'm going nuts! 我疯了!

    def __init__(self):

        file = self.gui()

Any ideas? 有任何想法吗? Thanks a bunch! 谢谢一群!

The way your code is now, filepath is assigned its value before your window even appears to the user. 现在,代码的方式是在您的窗口出现给用户之前为文件filepath分配值。 So there's no way the dictionary could contain the filename that the user eventually selects. 因此,字典无法包含用户最终选择的文件名。 The easiest fix is to put filepath = returned_values.get('filename') after mainloop , so it won't be assigned until mainloop ends when the user closes the window. 最简单的解决方法是将filepath = returned_values.get('filename') mainloop filepath = returned_values.get('filename') mainloop之后,因此直到用户关闭窗口时mainloop结束,它才被分配。

from Tkinter import *
from tkFileDialog import *

class trip_calculator:

    def gui(self):

        returned_values = {} 

        def open_file_dialog():
            returned_values['filename'] = askopenfilename()

        root = Tk()
        Button(root, text='Browse', command= open_file_dialog).pack()


        root.mainloop()

        filepath = returned_values.get('filename')
        return filepath

        root.quit()

print(trip_calculator().gui())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM