首页 > 解决方案 > 如何“合并”我的主程序和 GUI?

问题描述

只是为了明确区分我的问题和这里的许多其他问题:

已经编写了“主”程序(它具有类、函数和变量等)和一大块 GUI。

所以这不是关于如何用 tkinter 或 python 编写的问题,而是如何组合它们?

我应该从 GUI 运行程序吗?以及import各种变量、函数和类?如果是这样,我应该在需要时对每个项目import使用整个主程序吗?fromimport

我应该创建第三个导入主程序GUI 的程序吗?

我似乎找不到任何明确的答案,或者至少我似乎无法找到如何表达这个问题,因为所有搜索结果都指向如何编写 GUI,我已经掌握了要点。

标签: pythonuser-interfacetkinterimport

解决方案


这是我为我的一个项目所做的结构示例,其中包含一个服务器(您的实际主代码)、一个 GUI 和第三个我称为“App”的程序,它只运行 2。我创建了类似link_with_guilink_with_server这样的函数,您可以访问从服务器到您的 GUI 变量,反之亦然。

要运行此程序,您只需调用python app.py. 我if __name__ == '__main__'在服务器和 GUI 中添加了部分,因此您可以独立运行它们(用于测试目的)。

编辑:我用线程更新了我的代码。在服务器中,您有一个无限循环,每秒递增变量 self.count,在 GUI 中,如果您单击按钮,它将打印此计数。

应用程序 :

# app.py
from server import Server
from gui import GUI

class App:
    def __init__(self):
        self.gui = GUI()
        self.server = Server()
        self.link_parts()

    def link_parts(self):
        self.server.link_with_gui(self.gui)
        self.gui.link_with_server(self.server)

def main():
    app = App()
    app.gui.mainloop()

if __name__ == '__main__':
    main()

服务器 :

# server.py
import threading
import time

class Server:
    def __init__(self):
        self.count = 0
        thread = threading.Thread(target=self.counter)
        thread.daemon = True
        thread.start()

    def link_with_gui(self, gui):
        self.gui = gui

    def display(self):
        self.gui.chat_text.delete("1.0", "end")
        self.gui.chat_text.insert("insert", "This is Server count : {}".format(self.count))

    def counter(self):
        while True:
            self.count += 1
            time.sleep(1)
            print("self.count", self.count)

if __name__ == '__main__':
    server = Server()
    time.sleep(4)

图形用户界面:

# gui.py
import tkinter as tk
class GUI(tk.Tk): # Graphic User Interface
    def __init__(self):
        super().__init__()
        self.btn = tk.Button(master=self, text="Click Me")
        self.btn.pack()

        self.chat_text = tk.Text(self, width=20, height=3)
        self.chat_text.pack()

    def link_with_server(self, server):
        self.server = server
        self.btn.configure(command=self.server.display)

if __name__ == '__main__':
    gui = GUI()
    gui.mainloop()

推荐阅读