2012-12-06 49 views
2

我正在學習Python並遇到類似tkinter的類裝飾器的問題。只要我從不試圖裝飾Frame,我就可以讓tkinter工作。下面的代碼給了我沒有錯誤,沒有窗口。無論出於何種原因,我定義的類都永遠不會被定義。以下是我的代碼。下面是我基於tkinter的類似問題所做的測試。Python 3.2,Tkinter類聲明,類子類未定義

>>> from tkinter import * 
import tkinter 
class Apples: 
    def __init__(self, master): 
     frame = Frame(master) 
     frame.pack() 
     self.button = Button(frame, text="Quit", fg="blue", command=frame.quit) 
     self.button.pack(side=LEFT) 
     self.hellos = Button(frame, text="Hello", command=self.say_hello) 
     self.hellos.pack(side=LEFT) 
    def say_hello(self): 
     print("Hello World!") 
root = Tk() 
app = Apples(root) 
root.mainloop() 

沒有窗口出現。沒有錯誤。所以,我檢查類...

>>> test = Apples(root) 
Traceback (most recent call last): 
    File "<pyshell#54>", line 1, in <module> 
    test = Apples(root) 
NameError: name 'Apples' is not defined 
>>> 

我發現了一個類似的問題Creating buttons with Python GUI,並試圖從pythonMan代碼。我仍遇到相同的類聲明問題。

>>> from tkinter import * 

class Application(Frame): 
"""A GUI application with three button""" 

def __init__(self,master): 
    self.master = master 
    self.create_widgets() 



def create_widgets(self): 
    #"""Create three buttons""" 
    #Create first buttom 
    btn1 = Button(self.master, text = "I do nothing") 
    btn1.pack() 

    #Create second button 
    btn2 = Button(self.master, text = "T do nothing as well") 
    btn2.pack() 

    #Create third button 
    btn3=Button(self.master, text = "I do nothing as well as well") 
    btn3.pack() 

root = Tk() 
root.title("Lazy Button 2") 
root.geometry("500x500") 
app = Application(root) 
root.mainloop() 
>>> Application 
Traceback (most recent call last): 
    File "<pyshell#58>", line 1, in <module> 
    Application 
NameError: name 'Application' is not defined 
>>> 

我可以認爲某些東西沒有正確聲明,但沒有產生語法錯誤。任何幫助將不勝感激。

+1

您的第一個代碼片段適合我。我有兩個按鈕的應用程序窗口。 –

+0

我......不知所措。我將第一行代碼輸入行中,輸入IDLE。這次它工作得很好。它必須是一個縮進問題,但我找不到它。 – user1882948

+0

我無法回答這個已解答的問題7個小時。 – user1882948

回答

0

假設您的代碼已在問題的第二部分中正確複製,則說明您的類不正確。您有處於與class Application(Frame)相同的縮進級別。您的方法需要縮進,以便他們成爲課程的一部分。

您問題的第一部分中的代碼適合我。

1

我認爲你不需要「>>>」的標誌。

「from Tkinter import *」