2017-08-27 161 views
-2

我正在學習Python中Tkinter的包,我不明白下面的代碼:Python的 - 引用變量不存在

import tkinter as tk 

class Application(tk.Frame): 
    def __init__(self, master=None): 
     super().__init__(master) 
     self.pack() 
     self.create_widgets() 

    def create_widgets(self): 
     self.hi_there = tk.Button(self) 
     self.hi_there["text"] = "Hello World\n(click me)" 
     self.hi_there["command"] = self.say_hi 
     self.hi_there.pack(side="top") 

     self.quit = tk.Button(self, text="QUIT", fg="red", command=root.destroy) 
     self.quit.pack(side="bottom") 

    def say_hi(self): 
     print("hi there, everyone!") 

root = tk.Tk() 
app = Application(master=root) 
app.mainloop() 

據我瞭解self指的是類代碼時說: self.hi_there我期望這個類中的全局變量必須先聲明。 hi_there如何創建?

__init__方法中有什麼「master = None」的用法?如果我跳過=None部分,那麼它會不會是相同的,因爲我做的是app = Application(master=root)

+0

不知道你爲什麼認爲它們不存在。 –

+0

它在'self.hi_there = tk.Button(self)'創建。 – Ryan

+0

它被創建爲一個全局變量?這裏的自我意味着什麼?爲什麼不簡單地把「hi_there = tk.Button(self)」 – akerbeltz

回答

1

self指的是實例。 self.hi_there是一個實例變量。通過做app = Application(master=root)您創建Application的實例並將其保存到app。在你的情況下,selfapp

在創建屬性之前,您不需要聲明屬性(儘管在__init__中創建它們被認爲是一種很好的做法)。

考慮例如:

class A() 
    pass 

a = A() 
a.prop = 2 
print(a.prop) #=> 2 

關於master=None - 事實上,你可以,如果它是你的代碼只使用master,你知道你將它傳遞。

+0

但在這個例子中,它不會改變任何東西,如果我只是創建像'hi_there = tk.Button(self)'而不是'self.hi_there = tk.Button(self)'這樣的小部件,那麼這裏的自我意味着什麼? – akerbeltz

+0

@akerbeltz對不起,我沒有關注。你的問題是什麼? –

+0

我不知道如何解釋,我試着沒有自己的代碼在每個部件的代碼,它不會改變任何東西(我注意到)。爲什麼不簡單地把「hi_there = tk.Button(self)」? – akerbeltz

1

self指的是類的實例,併爲此self.hi_there = foo將創建一個新的實例變量,並將其分配給foo,如:

class Test: 
    def __init__(self): 
     self.foo = 'bar' 

a = Test() 
print(a.foo) 

# output: 
# bar 

而且master=None在默認None值設置爲master,除非你供應該值,例如:

app = Application() # here master will be None 
app = Application(master=root) # here master will be root 

This可以與任何功能一起使用,這裏是另一個例子:

def plus(num=0): 
    return num+num 

print(plus(1)) 
print(plus()) 

# output: 
# 2 
# 0