Python tkinter线程和窗口刷新
我正在使用python和tkinter构建一个可视化工具,可以刷新和可视化更新对象。现在,对象无法更改,因为线程不工作。任何帮助或常识都将不胜感激。我对线程和tkinter比较陌生 我要摄取的示例对象 我的可视化代码 有效的代码 不起作用的代码 在这个版本中,刷新可以工作,但线程不能。线程运行时,刷新不会检测到对象已更改Python tkinter线程和窗口刷新,python,multithreading,tkinter,Python,Multithreading,Tkinter,我正在使用python和tkinter构建一个可视化工具,可以刷新和可视化更新对象。现在,对象无法更改,因为线程不工作。任何帮助或常识都将不胜感激。我对线程和tkinter比较陌生 我要摄取的示例对象 我的可视化代码 有效的代码 不起作用的代码 在这个版本中,刷新可以工作,但线程不能。线程运行时,刷新不会检测到对象已更改 c.change_col('BLUE') 如果扩展threading.Thread类,则需要使用自定义功能重写run()方法。如果没有run方法,线程将立即死亡。您可以使用m
c.change_col('BLUE')
如果扩展
threading.Thread
类,则需要使用自定义功能重写run()
方法。如果没有run方法,线程将立即死亡。您可以使用my\u visual.is\u alive()
测试线程是否处于活动状态。问题是,由于self.root.mainloop()
,您的test.viz()
是一个无限循环,因此调用该函数后无法执行任何操作。解决方案是对test.viz()
使用线程
,并且不再需要类my_visual
的线程
我添加了一个时间。刷新前2秒的sleep
使其变为蓝色,否则在开始时颜色为蓝色
给你:
import threading
from tkinter import *
import time
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():
def __init__(self, col1):
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()
print("self.col1", self.col1, self.col1.color)
self.viz()
def exit(self):
self.root.quit()
self.root.destroy()
c = color1('RED')
test = my_visual(c)
t2 = threading.Thread(target = test.viz)
t2.start()
time.sleep(2)
print('Now you can change to blue when refreshing')
c.change_col('BLUE')
为什么需要穿线?虽然您的类继承了
threading.Thread
类,但是派生类没有包含run()
函数。这意味着start()
将不起任何作用。对于你的情况,使用线程是没有必要的。我肯定需要进一步调查。我想我要把线程转移到课堂之外,因为这个项目已经有点旋转了。感谢您的回复这真的很有帮助,我认为这是功能的发展方向。谢谢你提供的信息。
c = color1('RED')
test = my_visual(c)
test.viz()
c.change_col('BLUE')
import threading
from tkinter import *
import time
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():
def __init__(self, col1):
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()
print("self.col1", self.col1, self.col1.color)
self.viz()
def exit(self):
self.root.quit()
self.root.destroy()
c = color1('RED')
test = my_visual(c)
t2 = threading.Thread(target = test.viz)
t2.start()
time.sleep(2)
print('Now you can change to blue when refreshing')
c.change_col('BLUE')