【问题标题】:How to fix "not defined", but it is defined?如何修复“未定义”,但已定义?
【发布时间】:2019-08-12 16:33:19
【问题描述】:

我正在用 python 编码一些东西,我做了一个主类。我正在与 tkinter 合作。 在我的课堂上
主类(tk.Tk): 我有多个变量。我定义了两个变量。在它下面,还有另一个变量,它运行其他两个变量,我在上面写过。但后来它说,那些没有定义,但它是。错误消息:未定义名称“bruteforceABC”

class Main(tk.Tk):
    def bruteforceABC():
        for length in range(1, 3): # only do lengths of 1 + 2
            to_attempt = product(chars, repeat=length)
            for attempt in to_attempt:
                    print(''.join(attempt))

    def clear1():
        list = window.grid_slaves()
        for n in list:
            n.destroy()

    def clearforce():
        bruteforceABC()
        clear1()

我不知道,为什么它说,它没有定义。因为我已经定义了。我能做什么,我没有得到这个错误? 谢谢你的帮助!

【问题讨论】:

  • 请在您的问题中包含实际的错误信息。
  • 它说 WHAT 没有定义?
  • @BryanOakley 做到了。
  • @G.Anderson 它说,bruteforceABC 和 clear1 没有定义
  • 这两个名字是没有定义的;您定义的是实例方法,但您尝试将它们称为通用(非类)函数。由于它们是在类中定义的,因此您必须使用类的实例或类名来调用它们。我不确定你想用这个类设计做什么。

标签: python python-3.x visual-studio class tkinter


【解决方案1】:

您已将这些函数定义为类方法,但将它们称为通用方法。您应该使用self.method() 给他们打电话。

class Main(tk.Tk):
    @staticmethod
    def bruteforceABC():
        for length in range(1, 3): # only do lengths of 1 + 2
            to_attempt = product(chars, repeat=length)
            for attempt in to_attempt:
                    print(''.join(attempt))

    @staticmethod
    def clear1():
        list = window.grid_slaves()
        for n in list:
            n.destroy()

    def clearforce(self):
        self.bruteforceABC()
        self.clear1()

这样

【讨论】:

  • 谢谢。但我还有一个问题要问你。 (对不起,我忘记在帖子中写了)。在同一个课程中,我有这个:'''python'' if clearforce(): time.sleep(5) tk.Label(window, text="clear1").grid(row=0) else: tk. Button(window, text='ABC-Attack', command=show_entry_fields).grid(row=3, column=1, sticky=tk.W, pady=4) ' ' ' 它说,“清力”错过了一个自己。如果我写“clearforce(self)”,它会说,它没有定义。你知道,我在这里做错了什么吗?再次感谢。
  • 你应该使用self.clearforce()。这做了两件事,它告诉python您正在使用在类上定义的函数,并且还将您正在使用的类的实例作为第一个参数传递。相当于做MyClass.function_name(self)
  • 你是在课堂上调用这个吗?还是来自其他地方?如果是后者,请尝试调用该类的实例,Main().clearforce() 也是如此。
猜你喜欢
  • 2019-10-01
  • 1970-01-01
  • 2015-04-18
  • 2018-07-19
  • 2021-12-15
  • 1970-01-01
  • 2018-11-09
  • 2014-10-14
  • 2018-08-06
相关资源
最近更新 更多