繁体   English   中英

使用Tkinter的图形GUI抛出'NameError'

[英]Drawing GUI using Tkinter throws 'NameError'

我正在尝试提高编程技能,并且一直在做简单的Python项目。 我决定尝试使用GUI程序,并一直按照本教程进行指导。

我不太了解它,该链接将您带到教程的第三部分,而我遇到了一个问题。 我几乎完全复制了教程代码,只是更改了一些字符串以使其更接近我的最终目标。 (请参见下面的代码)

from tkinter import *

class Window(Frame):


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

# Creation of init_window
def init_window(self):

    #changing the title of our master widget
    self.master.title("Path Browser")

    #allowing the widget to take the full space of the root window
    self.pack(fill = BOTH, expand = 1)

    #creating a button instance
    browseButton = Button(self, text = "Browse")

    #placeing the button on my window
    browseButton.place(x=0, y=0)

root = Tk()

#size the window
root.geometry("400x300")

app = Window(root)
root.mainloop()

当我运行该代码时,它将生成一个窗口,但不包含任何按钮。 外壳程序输出以下错误消息:

Traceback (most recent call last):

File "C:/Users/mmiller3/Python/GUITest.py", line 3, in <module>
    class Window(Frame):
  File "C:/Users/mmiller3/Python/GUITest.py", line 31, in Window
    app = Window(root)
NameError: name 'Window' is not defined

我正在使用Python 3.7,并在Windows的IDLE中进行编辑。

我到处搜寻,发现没有发现有帮助。 例子中有我没有的错误(例如未引用/分配Tk())或根本不适用(某人的全局Window变量不起作用,显然是因为线程在Tkinter中不起作用)

我是Python的新手,通常对编程没有经验,因此任何建议/指导都将不胜感激。

Python使用空格定义范围。 您已经创建了一个名为Window的类,但是__init__()init_window()函数位于init_window()之外。

当您尝试在以下位置创建新窗口时:

app = Window(root)

您没有按预期正确实例化该类。

要解决此问题,请确保两个类方法均正确缩进,以便它们属于Window类:

from tkinter import *

class Window(Frame):


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

    # Creation of init_window
    def init_window(self):

        #changing the title of our master widget
        self.master.title("Path Browser")

        #allowing the widget to take the full space of the root window
        self.pack(fill = BOTH, expand = 1)

        #creating a button instance
        browseButton = Button(self, text = "Browse")

        #placeing the button on my window
        browseButton.place(x=0, y=0)

root = Tk()

#size the window
root.geometry("400x300")

app = Window(root)
root.mainloop()

以上为我工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM