【发布时间】:2021-12-11 17:23:25
【问题描述】:
我正在开发一个 Tkinter 桌面应用程序项目。当我需要使用运行后端代码的线程时,我开始跌跌撞撞。 我知道为了跨线程共享变量,我们应该使用全局变量。下面是最小的代码。
obj = None
class Frame:
def __init__(self, frame):
self.middle_frame = frame
self.start_button = ttk.Button(self.middle_frame, text='Start', command=self.start)
self.start_button.grid(row=0, column=0)
self.stop_button = ttk.Button(self.middle_frame, text='Stop', command=self.stop)
self.stop_button.grid(row=0, column=1)
self.stop_button.config(state='disabled')
def start(self):
self.thread = threading.Thread(target=self.start_connection)
self.thread.start()
self.start_button.config(state='disabled')
self.stop_button.config(state='normal')
def start_connection(self):
global obj
obj = MainManager() # Starts the Backend Loop
def stop(self):
global obj
obj.close_connection() # Want to break the loop here
self.thread.join()
self.stop_button.config(state='disabled')
self.start_button.config(state='normal')
运行此代码时,我得到 obj.close_connection() AttributeError:'NoneType' object has no attribute 'close_connection'。但我期待 obj 成为 MainManager() 的对象。
我哪里错了?帮我解决这个问题。
【问题讨论】:
-
您检查过
obj究竟是什么吗?显然它不是你想的那样。 -
我解决了。 @Oli 的答案正是我出错的地方
标签: python multithreading tkinter