2016-12-08 146 views
0

我想改變我的tkinter窗口上的圖標,我認爲我的問題源於我對課程缺乏理解。設置窗口圖標tkinter

我想知道爲什麼:

import tkinter 
root = tkinter.Tk() 
img = tkinter.PhotoImage(file = r'stockIcon.gif') 
root.tk.call('wm', 'iconphoto', root._w, img) 

root.mainloop() 

完美。但是:

import tkinter 

class Test: 
    def __init__(self): 
     self.root = tkinter.Tk() 
     self.img = tkinter.PhotoImage(file = r'stockIcon.gif') 
     self.root.tk.call('wm', 'iconphoto', root._w, img) 
     self.root.mainloop() 

test = Test() 

拋出NameError: name 'root' is not defined。我誤解了什麼?

+2

錯誤究竟是出了什麼問題告訴你。你已經定義了'self.root'而不是'root'。 –

回答

4

您需要通過self.root

改變訪問root

self.root.tk.call('wm', 'iconphoto', root._w, img) 

到:

self.root.tk.call('wm', 'iconphoto', self.root._w, img) 
+0

哇就是這樣。非常感謝!我現在覺得很愚蠢。 –

+1

沒問題,習慣面向對象編程需要時間。 –

+0

有沒有辦法避免訪問'root'的私有'_w'屬性? – phoenix