Python中__init__内变量跨类传递失败问题求助
解决Python类间传递__init__变量的问题(Tkinter/CustomTkinter场景)
问题场景
使用Tkinter和CustomTkinter开发程序时,需要将strength类中__init__方法内的self.strengthValue变量传递到savingThrows类中,用于计算并展示耐力值总和。已实例化strength类得到strengthObject并传入savingThrows的构造方法,但点击重新计算按钮时抛出错误:
AttributeError: type object 'strength' has no attribute 'strengthValue'
错误原因
在savingThrows类的recalculateEndurance方法中,错误地直接通过类名strength访问strengthValue属性,但strengthValue是实例属性(属于单个strength对象),而非类属性,不能通过类名直接调用。
修正方案
- 在
recalculateEndurance方法中,将strength.strengthValue.get()替换为self.strengthObject.strengthValue.get(),通过传入的实例访问属性。 - 修正
__init__方法内的代码缩进,确保窗口创建代码属于__init__方法范围。
修正后的完整代码
savingThrows类修正版
class savingThrows(): def __init__(self, strengthObject): self.strengthObject = strengthObject # create saving throws window self.savingThrows = ctk.CTkFrame(coreFrame, corner_radius=0, width=340, height=130) self.savingThrows.place(y=115, x=5) self.STTitle = ctk.CTkLabel(master=self.savingThrows, text="Saving Throws", font=ctk.CTkFont(size=14, weight="bold")).place(y=0, x=5) # endurance self.endurance = ctk.CTkLabel(master=self.savingThrows, text="Endurance", height=10, font=ctk.CTkFont(size=14, weight="bold")) self.endurance.place(y=25, x=15) self.enduranceProf = ctk.CTkComboBox(master=self.savingThrows, width=85, height=10, font=ctk.CTkFont(size=10), values=["Untrained", "Novice", "Apprentice", "Journeyman", "Expert", "Master", "Grandmaster"]) self.enduranceProf.place(y=25, x=140) self.enduranceDisplay = ctk.CTkEntry(justify="center", master=self.savingThrows, width=40, height=10, font=ctk.CTkFont(size=10), placeholder_text="000") self.enduranceDisplay.place(y=25, x=295) # recalculate button self.recalculateButton = ctk.CTkButton(master=self.savingThrows, text="Recalculate", width=55, height=10, font=ctk.CTkFont(size=10), command=self.recalculateEndurance) self.recalculateButton.place(y=25, x=230) def recalculateEndurance(self): enduranceDict = {"Untrained": 0, "Novice": 1, "Apprentice": 2, "Journeyman": 3, "Expert": 4, "Master": 5, "Grandmaster": 6} selectedValue = self.enduranceProf.get() self.enduranceDisplay.delete(0, "end") # 修正:通过实例访问strengthValue,而非类本身 total = enduranceDict[selectedValue] + self.strengthObject.strengthValue.get() self.enduranceDisplay.insert(0, str(total))
实例化代码(保持不变)
# Create a class objects and run them strengthObject = strength() savingThrowsObject = savingThrows(strengthObject)
关键说明
- 实例属性与类属性的区别:
strengthValue是在strength类的__init__中定义的,属于每个实例独有的属性,必须通过具体实例访问;类属性是直接定义在类内、__init__外的属性,可通过类名访问。 - 确保
__init__方法内的代码缩进正确,否则部分逻辑会被视为类的顶层代码,导致初始化逻辑失效。
内容的提问来源于stack exchange,提问作者Lemon Oeange and Lime
相关产品推荐
相关产品推荐

