2016-03-13 77 views
0

我在Python 2.7中使用Tkinter,並且遇到了我的類結構問題。下面是代碼:Python2.7 Tkinter包,範圍和類結構

import Tkinter as tk 
import tkFont 

class Display(): 

    def __init__(self, parent): 
     self.parent = parent 

     self._geom = '200x200+0+0' 
     parent.geometry("{0}x{1}+0+0".format(parent.winfo_screenwidth(), parent.winfo_screenheight())) 
     parent.overrideredirect(1) 

     parent.title('My App') 
     parent.configure(background='#000000') 
     parent.displayFont = tkFont.Font(family="Helvetica", size=150) 

     self.messageString="Hello" 
     self.message = tk.Message(self, text=self.messageString, bg="#000000", font=parent.displayFont, fg="#777777", justify="c") 
     self.message.place(relx=.5, rely=.5, anchor="c") 


def main(): 
    root = tk.Tk() 
    window = Display(root) 
    root.mainloop() 

if __name__ == '__main__': 
    main() 

我收到以下錯誤:

Traceback (most recent call last): 
    File "main_oop.py", line 31, in <module> 
    main() 
    File "main_oop.py", line 26, in main 
    window = Display(root) 
    File "main_oop.py", line 20, in __init__ 
    self.message = tk.Message(self, text=self.messageString, bg="#000000", font=parent.displayFont, fg="#777777", justify="c") 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2817, in __init__ 
    Widget.__init__(self, master, 'message', cnf, kw) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2081, in __init__ 
    BaseWidget._setup(self, master, cnf) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 2059, in _setup 
    self.tk = master.tk 
AttributeError: Display instance has no attribute 'tk' 

的代碼工作,直到我包括的init方法的最後四行,與使用tkFont行開始。

回答

1

您正試圖將Display的實例作爲其他小部件的父項實例(...tk.Message(self,...))。只有tkinter小部件可以是其他小部件的父母,並且self不代表小部件。

在這種特殊情況下,你必須使用self.parent作爲第一個參數:

self.message = tk.Message(self.parent, ...) 
+0

如果我使用tk.Message作爲方法的一部分,那麼,在「高清printMessage(個體經營,messageString)」,怎麼辦我寫下一行'self.message = tk.Message(self.parent,text = messageString,bg =「#000000」,font = parent.displayFont,fg =「#777777」,justify =「c」)'so該父母是否被承認? – interwebjill