【问题标题】:How can you use tkinter widgets across files in python?如何在 python 中跨文件使用 tkinter 小部件?
【发布时间】:2019-03-31 20:47:09
【问题描述】:

我对编程比较陌生,我注意到随着代码的增长,在 2 个文件(设置和主文件)中编写所有内容会变得非常混乱。 但是,当我将代码拆分为多个文件时,我遇到了无法导入 fileB.py intro FileA.py 并在文件 B 中使用文件 A 中的变量或小部件的问题(出现未定义名称错误)。

我在 UI 上使用 tkinter,所以我的主文件是 tk 循环 (main.py)。每个按钮指的是不同文件中的功能。它运行良好,直到我的函数包含按钮状态或条目文本。

这个例子是用 tkinter 的,但我在很多场合都遇到过这个问题,因为我相信我的代码结构。

文件 A (main.py)

import FileB
import tkinter
from tkinter import Checkbutton, Tk, Entry, BooleanVar

root = Tk() # initialize blank window
root.geometry("500x500")

# text entry
E1 = Entry(root, bd=5, width = 8)
E1.grid(row=0, column=1)

# Checkbox
CB_var = BooleanVar()
CB = Checkbutton(root, text="Get text", variable=CB_var, command=FileB.get_text() )
CB.grid(row=0, column=2)

root.mainloop()

文件B (FileB.py)

def get_text():
    if CB.var == True:
         entry_text = E1.get()
         E1.config(state=DISABLED)
         print(entry_text)
         E1.delete(0, END)
    elif CB.var == False:
         E1.config(state=NORMAL)
         print("Checkbox not selected")

由于在调用我的函数之前定义了 E1,我希望我的函数能够更改 E1 的状态,获取其文本并清空文本;就好像该函数在我的 main.py 中一样。

实际输出是未定义名称错误,因为 E1 不是我的 FileB 中的变量。

【问题讨论】:

    标签: python file tkinter widget structure


    【解决方案1】:

    由于FileBmain.py 导入,FileB 无法访问main.py 中的对象。需要通过函数参数传递main.py中的对象。

    建议将您的小部件放入一个类中,并将该类的实例传递给FileB.get_text() 函数。

    文件 A (main.py)

    from tkinter import Checkbutton, Tk, Entry, BooleanVar
    import FileB
    
    class GUI:
        def __init__(self, root=None):
            # text entry
            self.E1 = Entry(root, bd=5, width = 8)
            self.E1.grid(row=0, column=1)
            # Checkbox
            self.CB_var = BooleanVar()
            self.CB = Checkbutton(root, text="Get text", variable=self.CB_var, command=lambda: FileB.get_text(self))
            self.CB.grid(row=0, column=2)
    
    root = Tk() # initialize blank window
    root.geometry("500x500")
    GUI(root)
    root.mainloop()
    

    文件 B (FileB.py)

    from tkinter import DISABLED, NORMAL, END
    
    def get_text(gui):
        if gui.CB_var.get() == True:
             entry_text = gui.E1.get()
             gui.E1.config(state=DISABLED)
             print(entry_text)
             gui.E1.delete(0, END)
        else:
             gui.E1.config(state=NORMAL)
             print("Checkbox not selected")
    

    【讨论】:

    • 是的,类继承是我所缺少的确切概念!非常感谢,效果非常好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多