我在从 tkinter Button
命令返回变量时遇到问题。这是我的代码:
class trip_calculator:
def __init__(self):
file = self.gui()
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()
我只想返回文本文件的文件路径。 tkinter 窗口已打开,我可以浏览并选择文件,但它不会返回
路径。
最佳答案
按照您现在的代码方式,filepath
在您的窗口向用户显示之前就被分配了值。因此字典不可能包含用户最终选择的文件名。最简单的修复方法是将 filepath = returned_values.get('filename')
放在 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())
关于python - Tkinter 按钮命令返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19281280/