gpt4 book ai didi

python - Tkinter 按钮命令返回值?

转载 作者:行者123 更新时间:2023-12-01 05:35:07 32 4
gpt4 key购买 nike

我在从 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com