[英]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.