【发布时间】:2014-11-13 08:29:20
【问题描述】:
我有一个类,其中一些变量在第一种方法中声明为全局变量。另一种后续方法启动一个线程,问题是python无法识别t.start()之后的那些全局变量。以下是该程序的工作原理: 1) 用户可以单击 tkinter 窗口上的“是”按钮 2)然后程序开始将数据上传到数据库中。此步骤需要一段时间(2-5 分钟),为了防止 UI 在上传期间冻结,程序启动了一个执行 sql 内容的线程。同时,程序从窗口中清除小部件并用新的小部件(进度条和文本字段)替换它们。 3)上传完成后,程序再次用新按钮和滚动框刷新tkinter窗口。
这里是sn-p的代码:
class Application(tk.Frame):
def __init__(self, parent):
#do some init here..
def initUI(self):
global text1, text2, button_no, button_yes, progress_bar #here are the globals
frame1 = tk.Frame(self)
frame1.pack()
text1 = tk.Label(self, text="Do you want to upload a new log file?", background="white")
button_yes = tk.Button(self, text="YES", command=self.removeButtonYes)
button_no = tk.Button(self, text="NO", command=self.removeButtonNo)
text1.pack()
button_yes.pack()
button_no.pack()
self.pack(fill=tk.BOTH, expand=1)
def removeButtonNo(self):
#do something here
def removeButtonYes(self):
text1.pack_forget() #first three lines clear those original three widgets
button_no.pack_forget()
button_yes.pack_forget()
#then add some text with the progress bar
text2 = tk.Label(self, text="Transferring data. Please wait...", background="white")
text2.pack()
progress_bar = ttk.Progressbar(self, orient="horizontal", length=100, mode="indeterminate")
progress_bar.pack()
progress_bar.start(100)
#initialize a thread to prevent the UI from freezing during sql inserts
t = threading.Thread(target=self.writeLogtoDatabase)
t.start()
def writeLogtoDatabase(self):
#open db connection, upload data and close db
self.clearUI() #call a method to clear the progress bar and info text
def clearUI(self):
text2.pack_forget()
progress_bar.pack_forget()
它只是抛出以下错误消息:
Exception in thread Thread-1:
Traceback (most recent call last):
File "c:\python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "c:\python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Python27\test\testdb2.py", line 94, in writeLogtoDatabase
self.clearUI()
File "C:\Python27\test\testdb2.py", line 98, in clearUI
text2.pack_forget()
NameError: global name 'text2' is not defined
为什么?如您所见,我可以在声明它们的方法之外调用这些变量。这与线程有关 - 我不太熟悉的东西吗?
除非我没有忘记那些 text2 和进度条小部件,否则它们将显示在最后一个窗口中,这是不想要的功能。
【问题讨论】: