python – 创建第二个Toplevel小部件时,Threaded Tkinter脚本崩溃

栏目: Python · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/3567238/threaded-tkinter-script-crashes-when-creating-the-second-toplevel-widget
我有一个 Python

脚本,它使用Tkinter作为GUI.我的小脚本应该每隔X秒创建一个Toplevel小部件.当我运行我的代码时,第一个Toplevel小部件成功创建,但当它尝试创建第二个时,程序崩溃.

我正在做的是使用after方法每隔5秒与root的mainloop一起调用函数startCounting.每次调用此函数时,我都会将Toplevel小部件对象附加到列表中并启动一个新线程,希望它将运行新的mainloop.

如果有人能解决这个问题,我将非常感激.顺便说一下,这只是我目前用来解决我的问题的一个小脚本,这使我无法继续我的真实学校项目.

代码:

import threading,thread
from Tkinter import *


def startCounting():
    global root
    global topLevelList
    global classInstance

    topLevelList.append (Toplevel())
    topLevelList[len(topLevelList)-1].title("Child")
    classInstance.append(mainLoopThread(topLevelList[len(topLevelList)-1]))

    root.after(5000,startCounting)


class mainLoopThread(threading.Thread):
    def __init__(self,toplevelW):
        self.toplevelW = toplevelW
        threading.Thread.__init__(self)
        self.start()
    def run(self):
        self.toplevelW.mainloop()



global classInstance
classInstance = []
global topLevelList
topLevelList = []
global root

root = Tk() 
root.title("Main")
startCounting()
root.mainloop()
Tkinter仅设计为从主线程运行.见 the docs

Just run all UI code in the main  thread, and let the writers write to a  Queue object; e.g.

…接下来是一个实例,显示了将请求写入队列的辅助线程,主循环专门负责与Tk的所有直接交互.

许多对象和子系统不喜欢接收来自多个不同线程的请求,并且在GUI工具包的情况下,通常仅需要使用主线程并不罕见.

这个问题的正确 Python 架构总是用一个线程(主要的,如果必须的话)来为挑剔的对象或子系统服务;每个需要与所述子系统或对象交互的其他线程必须通过将请求排队到专用线程来获得它(如果某些请求需要结果,则可能在结果的“返回队列”上等待).这对于通用线程来说也是一个非常合理的Python架构(我在“果壳中的Python”中详细阐述了它,但这是另一个主题;-).

翻译自:https://stackoverflow.com/questions/3567238/threaded-tkinter-script-crashes-when-creating-the-second-toplevel-widget


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

New Dark Age

New Dark Age

James Bridle / Verso Books / 2018-7-17 / GBP 16.99

As the world around us increases in technological complexity, our understanding of it diminishes. Underlying this trend is a single idea: the belief that our existence is understandable through comput......一起来看看 《New Dark Age》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具