小编the*_*010的帖子

Python TKinter GUI 从多个线程更新——它是线程安全的吗?一些示例代码

我一直在研究 TKinter 遇到的这一问题,即根据其他线程的数据更新 GUI。正如许多人在网上建议的那样,我诉诸于使用队列轮询策略和self.root.after()方法。

这工作得很好,但我有一个问题,我需要更新嵌入在 TKinter GUI 中的 matplotlib 图,这样做会“停用”/将焦点从 GUI 的其他方面移开/可能会阻止GUI 的其他方面。具体来说,如果我在 TKinter 条目中输入内容并且 matplotlib 图更新,则光标不再位于条目中,并且我的输入过程已被中断。

为了解决这个问题,我想我应该尝试在一个单独的线程中更新 TKinter。现在,我在网上看到很多人声称TKinter不是线程安全的,但我也看到其他人说它线程安全的。我继续制作了一个示例程序,它似乎运行得很好:即使绘图更新,光标也可以保留在条目中。但我想知道的是,这个程序安全吗?或者它是否容易出现随机或可预测的故障?我该怎么做才能拥有线程安全的 GUI?

这是我的示例代码:

import Tkinter as tk
import threading
import Queue
import datetime
import math
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.gridspec as gridspec

gui_queue = Queue.Queue()

GUI_THEME_COLOR = 'lightblue'

##################################################
class MainGUI:
    def __init__(self, root):
        self.root = root
        self.root.title('TKinter GUI with Threaded Updates')
        self.root.minsize(width=800, height=300)
        self.root.config(background=GUI_THEME_COLOR) …
Run Code Online (Sandbox Code Playgroud)

python multithreading tkinter matplotlib thread-safety

5
推荐指数
0
解决办法
1622
查看次数