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

为何无法在类中通过函数触发另一个函数?出现NameError报错

问题解决:NameError: name 're_enter' is not defined

你的代码存在两个关键问题导致了该错误:

  • re_enter 作为类的实例方法,定义时缺少必要的 self 参数
  • 在 enter 方法中,没有通过实例对象(self)引用 re_enter 方法,直接写方法名会导致当前作用域找不到该名称

修正方案一(实例方法形式)

class Bio:
    # 其他类代码...

    def re_enter(self):  # 添加self参数,符合实例方法定义规范
        print('hi')

    def enter(self):
        ''' User has done all steps and continue'''
        button = tkinter.Button(self.frame, text='Enter', command=self.re_enter)  # 通过self调用实例方法
        button.grid(row=3, column=0, sticky='news', padx=20, pady=10)

修正方案二(静态方法形式,若无需访问类/实例属性)

如果 re_enter 不需要访问类或实例的任何属性和方法,可以定义为静态方法:

class Bio:
    # 其他类代码...

    @staticmethod
    def re_enter():
        print('hi')

    def enter(self):
        ''' User has done all steps and continue'''
        button = tkinter.Button(self.frame, text='Enter', command=Bio.re_enter)  # 通过类名调用静态方法
        button.grid(row=3, column=0, sticky='news', padx=20, pady=10)

内容的提问来源于stack exchange,提问作者Payam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:25:24