【问题标题】:NameError: name 'file' is not defined. while using tkinter ThreadNameError:名称“文件”未定义。在使用 tkinter 线程时
【发布时间】:2020-10-19 09:33:37
【问题描述】:

这是我的代码

from tkinter import Tk, Label, Button,filedialog,Text,END
from threading import Thread
from time import sleep

window = Tk()

window.title("Paper Database")
def openpaperfile():
    global file
    filename = filedialog.askopenfilename()
    with open(filename ,'r',encoding='utf-8') as f:
        file=f.readlines()
    Paper_message=Label(window,text='File uploaded')
    Paper_message.pack() 


def readFile():
    file_data=[]
    for i in file:
        file_data.append(file)
        sleep(1)
    

Paper_button=Button(window, text="Open Paper file", command=openpaperfile)
Paper_button.pack()

Read_button=Button(window, text="Read Paper file", command=Thread(target=readFile).start())
Read_button.pack()


window.geometry("720x480")
window.mainloop()

我得到的错误是NameError: name 'file' is not defined。 我只是想避免我的应用程序没有响应。在执行期间,我们可以显示等待,而不是使用线程,但总体目的是防止不响应

【问题讨论】:

    标签: python multithreading tkinter


    【解决方案1】:

    它应该是command=Thread(target=readFile).start,在start 附近没有()。如果您使用(),则在代码执行期间您正在调用(调用)该函数,而file 未定义,因此会出现错误。

    Read_button = Button(window, text="Read Paper file", command=Thread(target=readFile).start)
    

    请记住,这会引发错误。如果您多次单击该按钮。所以要修复它,将按钮命令更改为:

    Read_button=Button(window, text="Read Paper file", command=lambda: Thread(target=readFile).start())
    

    但是,这里是您的函数的改进版本:

    from tkinter import messagebox
    
    .... #same codes
    def readFile():
        try:
            file_data=[]
            for i in file:
                file_data.append(file)
                sleep(1)
        except NameError:
            messagebox.showerror('Choose file','Choose a file first')
    

    【讨论】:

    • 如果选择第二个文件并单击读取按钮,您的解决方案将引发异常。
    • @acw1668 我对 Q 的回答是,我没有寻找任何其他潜在的错误。不过,我现在已经更新了答案
    • 您可以简单地使用 lambda:command=lambda: Thread(target=readFile).start()。但是,您仍然需要检查 file 是否设置在 readFile() 中,以防永远不会调用 openpaperfile()
    【解决方案2】:

    下次请同时发布发生错误的行。我假设它在这条线上:

        for i in file:
    

    确实,file 没有在该范围内定义,因为您在该函数的顶部缺少 global file 声明。

    【讨论】:

    • 为什么readFile() 需要global file?在 openpaperfile() 声明时,它已经可用于全局范围
    • @CoolCloud Python 作用域的这一方面是微妙的:变量的范围是在解析时决定的,而不是在运行时决定的,它是根据变量分配的位置来决定的,未访问。在解析readFile() 时,不知道openpaperfile() 分配给全局file 的事实。如果顶层还有一个file = None,它会起作用,因为readFile() 将能够在外部范围内找到它。但即便如此,openpaperfile() 仍然需要global file,因为对file赋值 会在本地范围内创建第二个file 变量。
    • 是的,你说得对,但这里的问题是他直接调用了函数,那么按钮的作用是什么?
    猜你喜欢
    • 2020-04-20
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    相关资源
    最近更新 更多