我正在使用 python 和 tkinter 构建一个可视化工具,可以刷新和可视化更新对象。现在,该对象无法更改,因为线程不起作用。任何帮助或一般知识将不胜感激。我对线程和 tkinter 比较陌生。
我想要摄取的示例对象
class color1:
def __init__(self, color):
self.color = color
def change_col(self, new_color):
self.color = new_color
def pass_col(self):
return(self)
我的可视化代码
class my_visual(threading.Thread):
def __init__(self, col1):
threading.Thread.__init__(self)
self.start()
self.col1 = col1
def viz(self):
self.root = Tk()
btn1 = Button(self.root, text = 'Refresh', command = self.refresh)
btn1.pack()
frame = Frame(self.root, width = 100, height = 100, bg = self.col1.color)
frame.pack()
btn2 = Button(self.root, text = 'Close', command = self.exit)
btn2.pack()
self.root.mainloop()
def refresh(self):
self.root.quit()
self.root.destroy()
self.col1 = self.col1.pass_col()
self.viz()
def exit(self):
self.root.quit()
self.root.destroy()
有效的代码
c = color1('RED')
test = my_visual(c)
test.viz()
代码不起作用
在此版本中,刷新有效,但线程无效。当线程工作时,刷新不会发现对象已更改。
c.change_col('BLUE')
最佳答案
如果您扩展 threading.Thread
类,则需要使用自定义功能重写 run()
方法。如果没有 run 方法,线程会立即死亡。您可以使用 my_visual.is_alive()
测试线程是否处于事件状态。
关于Python tkinter 线程和窗口刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60217882/