这是我在这里的第一篇文章!
首先这是我的 project 的 github 链接(我也是 github 上的菜鸟) .
编辑:
所以这是我想做的一个例子,我有一个很大的 Tkinter 类,里面有框架、标签、菜单、按钮以及所有和一些功能。
我想将 UI 描述放入我的 MakeUI() 并将我的函数移动到另一个文件,但我仍然需要访问小部件。
< 主.py>
# -*- coding: utf-8 -*-
from tkinter import *
from Interface import *
Fenetre = Tk()
UI = MakeUI(Fenetre)
UI.mainloop()
UI.destroy()
<界面.py>
# -*- coding: utf-8 -*-
from tkinter import *
from tkinter.filedialog import *
class MakeUI(Frame):
def __init__(self, Fenetre, **kwargs):
# Héritage
Frame.__init__(self, Fenetre, width=1500, height=700, **kwargs)
self.pack(fill=BOTH)
self.FrameInfos = LabelFrame(self, text="Choix des paramètres", padx=2, pady=2)
self.FrameInfos.pack(fill="both", expand="yes", padx=5, pady=5)
self.MsgInfosCarte = Label(self.FrameInfos, text="Example", width=45)
self.MsgInfosCarte.pack(padx=2, pady=2)
def AfficherCarte(self):
self.MsgInfosCarte["text"] = "OK"
现在在这个例子中,我需要将 AfficherCarte 函数移动到另一个文件,如 MapFuncs.py 或其他文件。并且我希望MakeUI能够调用其他文件函数和其他文件函数来修改界面。
我做不到。
感谢您的帮助。
为了将修改 GUI 小部件的函数移动到单独的文件中,您可以简单地将 widget 实例(或存储该实例的对象)作为 函数的输入参数:
def AfficherCarte(UI):
UI.MsgInfosCarte["text"] = "OK"
<界面.py>
import tkinter as tk
from MapFuncs import AfficherCarte
class MakeUI(tk.Frame):
def __init__(self, Fenetre, **kwargs):
# Héritage
tk.Frame.__init__(self, Fenetre, width=1500, height=700, **kwargs)
self.pack()
self.FrameInfos = tk.LabelFrame(self, text="Choix des paramètres", padx=2, pady=2)
self.FrameInfos.pack(fill="both", expand="yes", padx=5, pady=5)
self.MsgInfosCarte = tk.Label(self.FrameInfos, text="Example", width=45)
self.MsgInfosCarte.pack(padx=2, pady=2)
# Call function from external file to modify the GUI
AfficherCarte(self)
如果您这样做是因为您的代码变得太大,另一种方法是将您的 GUI 分为界面的每个主要部分的单独类(参见 https://stackoverflow.com/a/17470842/4084269)。
我是一名优秀的程序员,十分优秀!