【问题标题】:Python3 class function definition confusion about NameError关于 NameError 的 Python3 类函数定义混淆
【发布时间】:2017-05-02 18:23:45
【问题描述】:

我是编程新手,这是我在网站上的第一篇文章。我确定我犯了一个愚蠢的错误,但我真的很感激朝着正确的方向前进。我正在尝试制作一个计算器,并希望制作一个为数字生成 Button 对象的函数。当我尝试运行它时,我得到了错误:

'NameError: name 'num_but_gen' is not defined'

代码如下:

from tkinter import * 

WINDOW_HEIGHT = 300
WINDOW_WIDTH = 325

class Window(Frame):

    def __init__(self, master = None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()

    def num_but_gen(self, disp, xloc=0, yloc=0, wid=0, hei=0):
        self.Button(text='{}'.format(disp),height=hei, width=wid)
        self.place(x=xloc, y=yloc)

    def init_window(self):
        self.master.title('Calculator')
        self.pack(fill=BOTH, expand=1)
        Button1 = num_but_gen('1', xloc=0, yloc=200, wid=40, hei=40)


root = Tk()
app = Window(root)
root.geometry("{}x{}".format(WINDOW_WIDTH,WINDOW_HEIGHT))
root.mainloop()

任何帮助将不胜感激!还可以向任何对如何在以后的帖子中更好地表达我的问题标题提出建议的人加分。

【问题讨论】:

  • 这是你类的方法。您必须将其称为self.num_but_gen(...),就像您对init_window() 所做的那样。

标签: python-3.x class tkinter


【解决方案1】:

jasonharper 是对的,你需要在num_but_gen 前面加上self,但是你的代码还有其他问题。

在num_but_gen:

  • 你的窗口类没有Button属性,所以你需要去掉Button前面的self.
  • 不是Window 实例,而是您要放置的按钮
  • 您不需要使用text='{}'.format(disp),text=disp 也是如此。

在init_window:

  • 您将num_but_gen 的结果存储在一个变量中,但此函数不返回任何内容,因此这是无用的(并且大写的名称不应用于变量,而只能用于类名)
  • 显示文本的按钮的宽度选项以字母而非像素为单位,其高度选项以文本行为单位,因此wid=40, hei=40 将创建一个非常大的按钮。如果你想以像素为单位设置按钮大小,你可以通过place 方法来代替。

下面是对应的代码:

import tkinter as tk

WINDOW_HEIGHT = 300
WINDOW_WIDTH = 325

class Window(tk.Frame):

    def __init__(self, master = None):
        tk.Frame.__init__(self, master)
        self.master = master
        self.init_window()

    def num_but_gen(self, disp, xloc=0, yloc=0, wid=0, hei=0):
        button = tk.Button(self, text=disp)
        button.place(x=xloc, y=yloc, height=hei, width=wid)

    def init_window(self):
        self.master.title('Calculator')
        self.pack(fill=tk.BOTH, expand=1)
        self.num_but_gen('1', xloc=0, yloc=200, wid=40, hei=40)


root = tk.Tk()
app = Window(root)
root.geometry("{}x{}".format(WINDOW_WIDTH,WINDOW_HEIGHT))
root.mainloop()

【讨论】:

    猜你喜欢
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-04
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2021-12-26
    相关资源
    最近更新 更多