"RuntimeError:从不同的公寓调用Tcl"tkinter和threading

use*_*652 5 multithreading tkinter tcl python-3.x

我想使用线程和tkinter(python 3.6)实现GUI .
当我运行GUIExecution.py时,会发生以下错误.在base_gui_class.py中的self.root.mainloop()上运行
" RuntimeError:从不同的appartment调用Tcl "
我在类的基础上实现它,三个代码文件如下所示.
可执行文件是GUIExecution.py.我花了很多时间来修复错误,但我还没能解决它.
请提出很多建议.
另外,如果我在python2环境中运行以下代码,它可以正常工作而不会出错.

GUIExecution.py

from base_gui_class import *

from base_class import *

speed = 1000
height = 500
width = 700

base_model = base_class()
gui = base_gui_class(base_model, speed, height, width)
base_model.visualize()
Run Code Online (Sandbox Code Playgroud)

base_class.py

class base_class():
    genes = []
    dicLocations = {}
    gui = ''
    best = ''
    time = 0

    def __init__(self):
        pass

    def visualize(self):
        if self.gui != '':
            self.gui.start()

    def registerGUI(self, gui):
        self.gui = gui
Run Code Online (Sandbox Code Playgroud)

base_gui_class.py

import threading
import tkinter as tk
import math
import threading
import time
class base_gui_class(threading.Thread):
    root = ''
    canvas = ''
    speed = 0
    base_model = ''
def __init__(self, base_model, speed, h, w):
    threading.Thread.__init__(self)
    self.base_model = base_model
    base_model.registerGUI(self)

    self.root = tk.Tk()

    self.canvas = tk.Canvas(self.root, height=h, width=w)
    self.canvas.pack()

    self.root.title("Test")
    self.speed = 1 / speed
def run(self):
    self.root.mainloop()
def update(self):
    time.sleep(self.speed)
    width = int(self.canvas.cget("width"))
    height = int(self.canvas.cget("height"))
    self.canvas.create_rectangle(0, 0, width, height, fill='white')
def stop(self):
    self.root.quit()
Run Code Online (Sandbox Code Playgroud)

Don*_*ows 11

对于非常好的第一和第二近似,Tk的核心是单线程.它可以在多个线程中使用,但只能在每个线程中单独初始化它.在内部,它广泛使用特定于线程的变量来避免需要大型锁定(也就是说,它没有像大型全局解释器锁一样)但这意味着你不能作弊.无论什么线程初始化Tk上下文必须是与该Tk上下文交互的唯一线程.这包括加载Tkinter模块,因此您只能有效地限制在主线程中使用Tkinter; 解决这个问题是严肃的专家.

我建议你让你的工作线程通过使用队列向它发布事件来对GUI进行更改(或者与关键部分和条件变量互锁,尽管我在实践中发现队列更容易).