Python tkinter 中的多处理

Multiprocessing in Python tkinter(Python tkinter 中的多处理)

本文介绍了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.

我已阅读 this previous question,我想您为什么在这里明确要求解决方案没有多线程.在 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 中的多处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Python tkinter 中的多处理

基础教程推荐