首页 > 解决方案 > 如何在不实例化的情况下从另一个类获取变量?

问题描述

我如何在不实例化类的情况下传递另一个类的变量?我不想实例化类的原因是因为我必须传递 self.master 这会弄乱我将变量传递到的类窗口。

class MainPageGUI:
    def __init__(self, master):

        self.master = master
        self.master.title("Jans Corp")
        self.master.configure(background='lightgrey')
        self.master.geometry("1200x800")

        listbox = tk.Listbox(self.master,width=150, height=35) # varibable i would like to use in the other class
        listbox.place(x=150, y = 130)

我想将变量传递给类:

class NewEmployee:
    def __init__(self, master): #Creating basic GUI to add employees

        self.master = master
        self.master.title("Jans Corp")
        self.master.configure(background="lightgrey")
        self.master.geometry("300x500")

        aa = MainPageGUI(self.master) ## my attempt at it, its wrong as the class get

        self.listbox = self.aa.listbox 

标签: pythonpython-3.xtkinter

解决方案


一般而言,“如何在没有实例化的情况下从另一个类中获取变量?”的答案 是“你不能”。

您的代码示例没有提供足够的信息来给出更具体的示例。例如,我们不知道您如何、何时或在何处创建 的实例MainPageGUI,或者您如何、何时以及在何处创建 的实例NewEmployee

我将假设您MainPageGUI在创建NewEmployee.

在您的情况下,您正在尝试MainPageGUI从另一个类中访问某些内容。您不想创建另一个 MainPageGUI. 相反,您需要的是对原始MainPageGUI. 由于该类必须在某处实例化,因此您只需在创建新的NewEmployee.

这意味着您需要定义NewEmployee如下内容:

class NewEmployee:
    def __init__(self, master, main_gui): 

        self.main_gui = main_gui
        ...

然后,在NewEmployee您需要引用列表框的任何地方,您都可以使用self.main_gui.listbox.

当然,这也需要MainGUI实际定义self.listbox. 现在,您的代码listbox = tk.Listbox(...)在需要时执行self.listbox = tk.Listbox(...)


推荐阅读