python - 如何在不实例化的情况下从另一个类获取变量?
问题描述
我如何在不实例化类的情况下传递另一个类的变量?我不想实例化类的原因是因为我必须传递 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
解决方案
一般而言,“如何在没有实例化的情况下从另一个类中获取变量?”的答案 是“你不能”。
您的代码示例没有提供足够的信息来给出更具体的示例。例如,我们不知道您如何、何时或在何处创建 的实例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(...)
。
推荐阅读
- webflow - 尽管有团队成员访问权限,但无法在 webflow 中编辑客户端模板
- c# - 同时运行两个任务
- python - 如何创建包含整数和浮点数的集合?
- python-3.x - 从现有的 pytroch 数据集继承而不重新下载数据
- bash - bash if 语句二元运算符
- bot-framework-composer - 如何在 Bot-Framework-Composer V 2.1.1 中添加翻译中间件
- angular - Angular——处理页面刷新
- google-places-api - Google Place API 限制为 5 条评论
- ruby-on-rails - 带有accepts_nested_attributes_for 和belongs_to 的Rails 嵌套表单
- ibm-cloud - IBM Cloud Container Registry:如何使用 CLI 删除一组(甚至全部)映像