首页 > 解决方案 > NameError:名称“文件”未定义。在使用 tkinter 线程时

问题描述

这是我的代码

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。我只是想避免我的应用程序没有响应。在执行期间,我们可以显示等待,而不是使用线程,但总体目的是防止没有响应

标签: pythonmultithreadingtkinter

解决方案


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

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')

推荐阅读