Python Tkinter中的多处理 [英] Multiprocessing in Python tkinter

查看:69
本文介绍了Python Tkinter中的多处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用多线程的情况下在python中运行多个进程?例如,考虑以下问题:-

How to run multiple processes in python without multithreading? For example consider the following problem:-

我们必须制作一个Gui,它具有一个用于启动函数的开始按钮(例如,打印所有整数),并且具有一个停止按钮,以便单击该按钮可以停止该函数.

We have to make a Gui,which has a start button which starts a function(say, prints all integers) and there is a stop button, such that clicking it stops the function.

如何在Tkinter中做到这一点?

How to do this in Tkinter?

推荐答案

然后,您需要将Button小部件与启动工作线程的函数绑定在一起.例如:

Then you need to bind the Button widget with the function which starts the working thread. For example:

import time
import threading
import Tkinter as tk

class App():
    def __init__(self, root):
        self.button = tk.Button(root)
        self.button.pack()
        self._resetbutton()
    def _resetbutton(self):
        self.running = False
        self.button.config(text="Start", command=self.startthread)
    def startthread(self):
        self.running = True
        newthread = threading.Thread(target=self.printints)
        newthread.start()
        self.button.config(text="Stop", command=self._resetbutton)
    def printints(self):
        x = 0
        while self.running:
            print(x)
            x += 1
            time.sleep(1) # Simulate harder task

使用self.running方法,仅可以通过更改其值来优雅地结束线程.请注意,使用多个线程可以避免在执行printints时阻塞GUI.

With the self.running approach, you can end the thread gracefully only by changing its value. Note that the use of multiple threads serves to avoid blocking the GUI while printints is being executed.

我已阅读上一个问题,我想为什么您在这里明确要求解决方案没有多线程.在Tkinter中,此解决方案可用于其他线程必须与GUI部件进行通信的情况.例如:在渲染某些图像时填充进度条.

I have read this previous question and I suppose why you explicitly asked here for a solution without multithreading. In Tkinter this solution can be used in a scenario where the other threads have to communicate with the GUI part. For example: filling a progressbar while some images are being rendered.

但是,正如评论中指出的那样,这种方法对于仅打印数字来说太复杂了.

However, as it has been pointed in the comments, this approach is too complex for just printing numbers.

此处,您可以找到很多有关Tkinter的信息和更多示例.

Here you can find a lot of information and more examples about Tkinter.

既然您的新问题已经解决,我将在此处更改代码以阐明最后一点.

Since your new question has been closed, I'll change the code here to clarify the last point.

这篇关于Python Tkinter中的多处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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