You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:11:04