python - 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
。我只是想避免我的应用程序没有响应。在执行期间,我们可以显示等待,而不是使用线程,但总体目的是防止没有响应
解决方案
应该是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')
推荐阅读
- maven - jmeter-maven-plugin 使用 logback.xml 将日志加载到 Elastic 绕过 Logstash 配置
- antlr4 - ANTLR 有 VPAT 吗?
- python - 使用 pipenv 安装 bs4 时出错
- scala - 带有泛型的隐式 scala 类
- ios - iOS 13 UISearchController 书签
- node.js - 安装 Angular Material 后的 Angular 编译警告
- timer - 在 CAPL 中创建一个可暂停的计时器
- google-apps-script - 粘贴到错误的单元格
- javascript - Google Apps 脚本删除自动电子邮件中的 html 标签
- typescript - 在 TypeScript 中复制相同键属性错误