使用CustomTkinter开发习惯追踪器时遇AttributeError错误求助
问题分析
报错AttributeError: 'str' object has no attribute 'create_habit_window'的核心原因:
- 直接通过类
CreateHabit调用实例方法create_habit,并把字符串self.k当作self参数传入,导致create_habit方法内的self变成字符串对象,而字符串不存在create_habit_window属性。 CreateHabit.commit_habit的调用方式同样错误,直接用类调用实例方法会缺失self参数。
修复步骤
1. 修正CreateHabit类实现
调整方法调用逻辑,确保实例方法通过实例调用:
class CreateHabit: def create_habit(self): self.create_habit_window = customtkinter.CTk() self.create_habit_window.geometry('500x500') self.new_habit_entry = customtkinter.CTkEntry(self.create_habit_window, placeholder_text='Enter Habit Name') self.new_habit_entry.pack(pady=30) self.options = ['Daily', 'Weekly', 'Monthly'] self.new_habit_Combo = customtkinter.CTkComboBox(self.create_habit_window, values=self.options) self.new_habit_Combo.pack(pady=20) # 改为调用当前实例的commit_habit方法 self.new_habit_button = customtkinter.CTkButton(self.create_habit_window, text='Create New Habit', command=self.commit_habit) self.new_habit_button.pack(pady=30) self.create_habit_window.mainloop() def commit_habit(self): # 补充习惯创建的具体逻辑 habit_name = self.new_habit_entry.get() habit_frequency = self.new_habit_Combo.get() print(f"已创建习惯:{habit_name},频率:{habit_frequency}") self.create_habit_window.destroy()
2. 修正按钮的command绑定逻辑
先创建CreateHabit实例,再将实例的create_habit方法绑定为按钮命令(避免直接调用方法导致提前执行):
# 先实例化CreateHabit类 self.create_habit_instance = CreateHabit() # 绑定命令为实例的create_habit方法,不要加括号 self.create_new_habit_button = customtkinter.CTkButton( self.main_window, text='Create New Habit', command=self.create_habit_instance.create_habit, fg_color='green' ) self.create_new_habit_button.pack(pady=20)
额外注意事项
- 不要在创建组件的同一行调用
.pack(),因为.pack()返回None,会导致self.create_new_habit_button变成None,后续无法对按钮进行操作。 - 如果
self.k是需要传递给CreateHabit的参数,可以给类添加__init__方法接收:
class CreateHabit: def __init__(self, k): self.k = k
实例化时传入参数:
self.create_habit_instance = CreateHabit(self.k)
内容的提问来源于stack exchange,提问作者Kael Scanes
相关产品推荐
相关产品推荐

