如何在 tkinter 后台运行一个函数 [英] How to run a function in the background of tkinter
问题描述
我是 GUI 编程的新手,我想用 tkinter 编写一个 Python 程序.我想让它做的就是在后台运行一个可以通过 GUI 影响的简单函数.
I am new to GUI programming and I want to write a Python program with tkinter. All I want it to do is run a simple function in the background that can be influenced through the GUI.
该函数从 0 到无穷大计数,直到按下按钮.至少这是我想要它做的.但是我不知道如何在后台运行这个函数,因为 tkinter 的 mainloop() 一直在控制.如果我在无限循环中启动该函数,则无法执行 mainloop() 并且 GUI 已死.
The function counts from 0 to infinity until a button is pressed. At least that is what I want it to do. But I have no idea how I can run this function in the background, because the mainloop() of tkinter has control all the time. And if I start the function in an endless loop, the mainloop() cannot be executed and the GUI is dead.
我想在每个循环后将控制权返回给 mainloop(),但是如何在没有用户触发事件的情况下将控制权从 mainloop() 返回到 runapp 函数?
I would like to return control back to the mainloop() after each cycle, but how can I get the control back from the mainloop() to the runapp-function without a user-triggered event?
以下是一些杀死 GUI 的示例代码:
Here is some sample code that kills the GUI:
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="START", command=self.runapp)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="RESTART", command=self.restart)
self.hi_there.pack(side=LEFT)
self.runapp()
def restart(self):
print "Now we are restarting..."
def runapp(self):
counter = 0
while (1):
counter =+ 1
time.sleep(0.1)
推荐答案
你会在另一个问题中找到答案 Tkinter 在线程中加载 Icon 和 tk.mainloop 时锁定 python.
You will find the answer in this other question Tkinter locks python when Icon loaded and tk.mainloop in a thread.
简而言之,您需要有两个线程,一个用于 tkinter,一个用于后台任务.
In a nutshell, you need to have two threads, one for tkinter and one for the background task.
这篇关于如何在 tkinter 后台运行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!