通过后台线程访问Tkinter的Text小部件会导致崩溃 [英] Access to Tkinter's Text widget by background thread cause crashes

查看:75
本文介绍了通过后台线程访问Tkinter的Text小部件会导致崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的tkinter应用程序,其中使用了两个线程.他们的任务是将数字写入小部件,例如标签和文本.一个线程由按钮(单击事件)触发,第二个线程作为后台线程执行.

I created a simple tkinter app, where have used two threads. Their task is to write numbers to widgets such as label and text. One thread is triggered by button (click event) and second is executed as a background thread.

import Tkinter as tk
from ttk import *
from Tkconstants import *
import threading, thread, time

def tl1(text,counter):
    while True:
        text.insert(END,counter)
        counter += 1
        time.sleep(2)

def tl2(label,counter):
    while True:
        label['text'] = counter
        counter += 1
        time.sleep(1)

class mainWindow():
    def __init__(self, master):
        self.master = master
        self._initLayout()

    def _initLayout(self):

        #button
        self.button = tk.Button(self.master, text="thread1_start", command = self._task1)
        self.button.pack()

        #label
        self.label = tk.Label(self.master)
        self.label.pack()

        #text
        self.text = tk.Text(self.master, width=30)
        self.text.pack()

    def _task1(self):
        t1 = thread.start_new_thread(tl1,(self.text,1))

    def _task2(self):
        t2 = thread.start_new_thread(tl2,(self.label,1000))

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.mainWindow = mainWindow(self)

        self.mainWindow._task2() #background_thread

app = App()
app.mainloop()

通过这种方式,一切正常,但是如果我们更改后台线程以在文本小部件上显示结果,则整个应用程序将冻结.
为什么后台线程可以与标签正常通信,但会导致文本小部件出现问题?有什么办法可以正常运行吗?

In this manner everything works fine, but if we change the background thread to display results on text widget, the whole app freezes.
Why background thread works fine communicating with label but causes problems with text widget? Is there any way to run it properly?

推荐答案

Tkinter不是线程安全的.您只能从创建它们的线程中访问窗口小部件.您的线程将需要将数据放入线程安全的队列中,而您的GUI线程将需要轮询该队列.

Tkinter isn't thread safe. You can only access widgets from the thread that created them. Your threads will need to put data on a thread-safe queue, and your GUI thread will need to poll the queue.

在您的特定情况下,您根本不需要线程.您可以使用tkinter after方法定期运行代码.

In your particular case you don't need threads at all. You can use the tkinter after method to run code periodically.

这篇关于通过后台线程访问Tkinter的Text小部件会导致崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆