我如何在不实例化该类的情况下从另一个类传递变量?我不想实例化类的原因是因为我必须传递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
答案 0 :(得分:1)
一般而言,“如何在不实例化的情况下从另一个类获取变量”的答案是?是“你做不到”。
您的代码示例未提供足够的信息来给出更具体的示例。例如,我们不知道如何创建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(...)
。