让python通过tkinter等待变量的设置

让python通过tkinter等待变量的设置,python,button,tkinter,block,wait,Python,Button,Tkinter,Block,Wait,我在tkinter中遇到了这个问题,我想设置文档的源代码,这样我的代码就可以使用搜索按钮和askopenfilename在python中处理文件 这是我的代码片段 ... from tkinter import * from tkinter import filedialog root = Tk() root.title("Alpha") root.iconbitmap('images\alpha.ico') def search(): global location ro

我在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\u txt
变量中的
location
未定义,我完全理解。我想我的python代码没有等待我按下程序窗口中的按钮并搜索我的文件,因此可以定义
位置。在尝试定义
input\u txt
之前,如何使python等待
open()
返回
location
的值

我试过了

import time
...
location = ''
open_button = Button(root, text="Open File", command=open).pack()
while not location:
    time.sleep(0.1)
然而,这会导致程序冻结,我知道睡眠不是最好的选择。 有什么建议吗?

关于你的问题 正如布姆金建议的那样,我建议将
输入\u txt=open(location,…)
行移动到
搜索功能中。这样,一旦按下按钮并定义了
位置
,程序将仅尝试从
位置
打开

如果有其他事情发生,您可以创建另一个函数并调用该函数:

def file_handling(location):
    input_txt = open(location, "r", encoding="utf8")
    ... #anything using input_txt

def search():
    root.filename = filedialog.askopenfilename(initialdir="/", title="Select A File",
                                               filetypes=(("txt files", "*.txt"), ("All Files", "*.*")))
    file_handling(root.filename)

open_button = Button(root, text="Open File", command=search)
open_button.pack()
...
root.mainloop()
问题是Tkinter对象在到达mainloop之前不会执行任何操作,但是一旦进入mainloop,就不能返回并填充任何内容。所以你想做的每件事都必须与某种输入联系在一起:比如按下按钮(或者击键,或者鼠标)

在这种情况下,您需要设置
位置
,但必须等待调用mainloop,按钮开始接收输入。但到那时,您已经通过了需要
位置的线路,无法返回。这就是为什么我建议从
search
函数调用
input\u txt
行的原因——因为在您获得位置之前不会调用它

这有点冗长,但我希望它能说明问题

旁注 我还建议您单独声明和打包小部件。也就是说,改变这一点:

open_button = Button(root, text="Open File", command=search).pack()
为此:

open_button = Button(root, text="Open File", command=search)
open_button.pack()

否则,您将存储
pack()
(即
None
)的值,而不是存储您的小部件(
按钮
对象)。

我不完全理解您在这里试图实现的目标。我知道您希望根据用户的GUI输入打开一个文件,但在您的第一个代码片段中,我不明白为什么要定义一个全局变量。你也可以在你的函数中操作输入文件。我认为你不了解GUI事件处理和编程。参见@Bryan Oakley对的回答。Tkinter对象在mainloop之前不是空闲的,mainloop是一个无限循环,可以显示/绘制它们,并在屏幕上停留,直到终止。