Python tkinter线程和窗口刷新

2024-06-08 19:48:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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')

Tags: 对象代码selfinittkinter可视化defcol
2条回答

如果扩展threading.Thread类,则需要使用自定义功能重写run()方法。如果没有run方法,线程将立即死亡。您可以使用my_visual.is_alive()测试线程是否处于活动状态

问题是test.viz()是一个无限循环,因为self.root.mainloop(),所以一旦调用了该函数,就无法执行任何操作。解决方案是对test.viz()使用thread,并且不再需要类my_visual的线程

在刷新使其变为蓝色之前,我添加了2秒的time.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')

相关问题 更多 >