运行 仅当框架在 tkinter 中打开时守护进程

run daemons only when frames are opened in tkinter

我创建了 3 个框架,每个框架都有自己的守护进程,为了在框架之间导航,我正在使用堆栈 method.everything 工作正常,但我的问题是所有守护进程都 运行ning 甚至虽然我没有打开它们各自的框架,但我知道我正在将框架加载到堆栈中,这就是所有守护进程启动 运行ning 的原因。 但是我希望这些守护进程仅在打开它们的框架时才 运行,所以我有什么办法可以做到这一点。 示例- Mainfile.py

import tkinter as tk                # python 3
from tkinter import font  as tkfont # python 3
#import Tkinter as tk     # python 2
#import tkFont as tkfont  # python 2
from Page1 import PageOne
from Page2 import PageTwo
class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

上面的文件现在是那个文件中的一个主文件我正在导入另外两个有自己的守护进程的框架, 文件-Page1

import threading
import tkinter as tk
class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack() 
        thread1 = threading.Thread(target=self.func)
        thread1.daemon=True
        thread1.start()
      
    def func(self):
        print("this is thread1")

文件-第2页

import threading
import tkinter as tk
class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()
        thread2 = threading.Thread(target=self.func)
        thread2.daemon=True
        thread2.start()
      
    def func(self):
        print("this is thread2")

在我 运行 整个程序之后,我可以看到两个守护进程给出答案,但我希望它们 运行 只有在它们的框架打开后,例如当框架 PageOne 打开时,它的thread-threa1 应该 运行 打印答案。

有什么方法可以做到吗?

注意:这只是我给出的一个简单示例,但实际上我正在处理实时硬件值,因此通过使用线程和守护进程,我可以生成 UI 和 Processing 东西硬件并行

简单的解决方案是在需要时才创建框架。您可以通过修改 show_frame 来按需创建框架。

首先,您需要将初始化 UI 的代码修改为 而不是 创建框架。相反,它可以只创建从页面名称到页面 class 的映射。您需要删除以 for F in (StartPage, PageOne, PageTwo): 开头的循环并将其替换为如下内容:

self.frames = {
    "StartPage": StartPage, 
    "PageOne": PageOne, 
    "PageTwo": PageTwo,
}

接下来,修改 show_frame 以销毁任何现有框架,然后创建新框架。它应该看起来像这样:

def show_frame(self, page_name):
    # destroy the old frame
    for child in container.winfo_children():
        child.destroy()

    # create the new frame
    frame_class = self.frames[page_name]
    frame = frame_class(parent=self.container, controller=self)
    frame.pack(fill="both", expand=True)

另一种解决方案是保留原始代码,但仅在显示框架时才启动线程。在这个问题的已接受答案中可以看到显示框架时如何 运行 函数的示例: