如何在Python Tkinter/CustomTkinter的不同类与框架间访问数据?
解决方案
你不需要在A类中重新实例化B类,Main.py里已经创建了唯一的B实例cl_B,直接复用这个实例即可,下面提供两种简单可行的方法:
方法一:初始化A时传入B实例
修改Main.py中创建A类实例的代码,把已有的cl_B传递给A;同时修改A类的构造函数,接收并保存这个B实例:
修改后的Main.py片段
# ... 其他代码不变 self.cl_B = B(self, self.B_frame) # 创建A实例时传入已有的cl_B self.cl_A = A(self, self.A_frame, self.cl_B)
修改后的A.py
import customtkinter import tkinter from B import * class A: def __init__(self, root, frame, b_instance): self.root = root self.frame = frame self.b_instance = b_instance # 保存B类实例的引用 self.value_1_label = customtkinter.CTkLabel(self.frame, text="Value_1").place(x=20, y=150) self.value_1_entry = customtkinter.CTkEntry(self.frame) self.value_1_entry.place(x=120, y=150) self.berechnung_button = customtkinter.CTkButton(self.frame, text="Calculate", fg_color="#204A94", command=self.calculate) self.berechnung_button.place(x=20, y=700) def calculate(self): try: # 获取输入值并转换为数字 val1 = float(self.value_1_entry.get()) val2 = float(self.b_instance.value_2_entry.get()) result = val1 + val2 print(f"求和结果:{result}") # 如需在GUI显示结果,可添加标签 # customtkinter.CTkLabel(self.frame, text=f"结果:{result}").place(x=20, y=730) except ValueError: print("请输入有效的数字")
方法二:通过App实例(root)直接访问B实例
A类的self.root就是Main.py中的App实例,而App里已经保存了cl_B,所以可以直接通过self.root.cl_B获取B实例:
修改后的A.py(无需改动Main.py)
import customtkinter import tkinter from B import * class A: def __init__(self, root, frame): self.root = root self.frame = frame self.value_1_label = customtkinter.CTkLabel(self.frame, text="Value_1").place(x=20, y=150) self.value_1_entry = customtkinter.CTkEntry(self.frame) self.value_1_entry.place(x=120, y=150) self.berechnung_button = customtkinter.CTkButton(self.frame, text="Calculate", fg_color="#204A94", command=self.calculate) self.berechnung_button.place(x=20, y=700) def calculate(self): try: val1 = float(self.value_1_entry.get()) # 通过root访问App中的cl_B实例 val2 = float(self.root.cl_B.value_2_entry.get()) result = val1 + val2 print(f"求和结果:{result}") except ValueError: print("请输入有效的数字")
两种方法都能避免重复创建B实例导致的控件显示问题,推荐第一种方法,它更符合面向对象的依赖注入原则,代码耦合度更低。
内容的提问来源于stack exchange,提问作者Steffen
相关产品推荐
相关产品推荐

