长过程中与Tkinter窗口的交互作用

2024-10-01 15:32:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基本的python类,它使用标准的Tkinter库创建一个窗口:

import Tkinter

class GUI(Tkinter.Tk):

    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def lock_func(self):
        while 1==1:
            print "blah"

    def initialize(self):
        self.processBtn = Tkinter.Button(self, text="Process", command=self.lock_func)
        self.processBtn.pack()        

app = GUI(None)
app.mainloop()

当我按下Process按钮时,窗口没有响应。 我希望能够在lock_func运行时关闭程序(使用x按钮)。在


Tags: selflockapp标准inittkinterdefgui
3条回答

您可以使用generator来保持循环中的状态,并使用yield将控制权交回主循环。然后使用self.after反复调用生成器的next方法来模拟while True的效果,但要以对Tkinter的主循环友好的方式进行。在

import Tkinter as tk

class App(object):
    def __init__(self, master):
        self.master = master
        self.initialize()

    def lock_func(self):
        def step():
            while True:
                print("blah")
                self.nextstep_id = self.master.after(1, nextstep)
                yield
        nextstep = step().next
        self.nextstep_id = self.master.after(1, nextstep)

    def stop(self):
        self.master.after_cancel(self.nextstep_id)
        print("stopped")

    def initialize(self):
        self.nextstep_id = 0
        self.process_button = tk.Button(self.master, text="Process",
                                        command=self.lock_func)
        self.stop_button = tk.Button(self.master, text="Stop",
                                     command=self.stop)        
        self.process_button.pack()
        self.stop_button.pack(expand='yes', fill='x')

root = tk.Tk()
app = App(root)
root.mainloop()

您可以使用window.update()方法来保持GUI的活动性和功能性。在根mainloop期间,这是自动发生的,但如果您要延长主循环,则最好自己手动执行。将window.update()放入正在花费一段时间的循环中。注意:windowTk()对象

一种方法是使用线程:

import Tkinter
import thread

class GUI(Tkinter.Tk):

    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def lock_func(self):
        while 1==1:
            print "blah"

    def initialize(self):
        self.processBtn = Tkinter.Button(self, text="Process", command=lambda: thread.start_new_thread(self.lock_func, ()))
        self.processBtn.pack()        

app = GUI(None)
app.mainloop()

但是,它将一直打印,直到您关闭Python控制台。在

要停止它,可以使用另一个更改变量的按钮:

^{pr2}$

相关问题 更多 >

    热门问题