【发布时间】:2020-03-19 23:05:34
【问题描述】:
我在使用 tkinter 时遇到了这个问题,我想在其中设置文档的来源,以便我的代码可以使用搜索按钮和 askopenfilename 在 python 中处理文件。
这是我的代码片段。
...
from tkinter import *
from tkinter import filedialog
root = Tk()
root.title("Alpha")
root.iconbitmap('images\alpha.ico')
def search():
global location
root.filename = filedialog.askopenfilename(initialdir="/", title="Select A File",
filetypes=(("txt files", "*.txt"), ("All Files", "*.*")))
location = root.filename
open_button = Button(root, text="Open File", command=search).pack()
input_txt = open(location, "r", encoding="utf8")
...
root.mainloop()
问题:当我运行程序时,窗口会打开片刻,我立即收到input_txt 变量中的location 未定义的错误,我完全理解。我想我的 python 代码并没有等我按下程序窗口中的按钮并搜索我的文件,因此可以定义 location。在尝试定义input_txt之前,如何让python等待open()返回location的值?
我试过了
import time
...
location = ''
open_button = Button(root, text="Open File", command=open).pack()
while not location:
time.sleep(0.1)
然而,这会导致程序冻结,我知道睡眠在这里不是最好的选择。 有什么建议吗?
【问题讨论】:
-
我不完全明白你在这里想要达到的目标。我知道您想根据用户的 GUI 输入打开文件,但是在您的第一个代码 sn-p 中,我不明白您为什么要定义全局变量。你也可以在你的函数中操作输入文件。
-
我认为您不了解 GUI 事件处理和编程。请参阅@Bryan Oakley 对Tkinter — executing functions over time 的回答。
标签: python button tkinter block wait