2011-10-15 144 views
1

我和我的朋友正在製作一個顯示4個單選按鈕和文本的窗口,我們正努力在底部添加兩個按鈕。將單選按鈕添加到Tkinter

這裏是我們的代碼:

from Tkinter import * 

import time 

class App: 

    def __init__(self, master): 


     frame = Frame(master) 
     frame.pack() 

     v = IntVar() 

     Radiobutton(master, text="0 for not at all", variable=v, value=1).pack(side=TOP) 

     Radiobutton(master, text="1 for somewhat", variable=v, value=2).pack(side=TOP) 

     Radiobutton(master, text="2 for moderatly", variable=v, value=3).pack(side=TOP) 

     Radiobutton(master, text="3 for a lot", variable=v, value=4).pack(side=TOP) 

     self.button = Button(master, text="BACK", fg="red", command=self.button6) 
     self.button.pack(side=BOTTOM) 

     self.button = Button(master, text="NEXT", fg="red", command=self.button5) 
     self.button.pack(side=BOTTOM) 

    def button6(self): 
     print "Sam is awesome!GAJONGA" 

    def button5(self): 
     print "PYTHON FOR THE WIN! GIAN SAYS PYTHON = FILTHY" 

w = Label(master, text="1. Anxiety, nervousness, worry or fear") 
w.pack() 

master = Tk() 


master.mainloop() 

運行這給了我們以下錯誤:

Traceback (most recent call last): 
    File "/Volumes/CHROME USB/STORAGE/TKinker GUI/Radiobutton example.py", line 36, 
    in <module> 
    w = Label(master, text="1. Anxiety, nervousness, worry or fear") 
NameError: name 'master' is not defined 

回答

3

您需要實際初始化App類才能完成任何操作。標籤應該與其他所有小部件一起放入init方法中。通常情況下,你會把所有的小部件放在框架內(例如,Radiobutton(frame,text = ...),但是如果你不打算使用框架,那麼就不需要創建它並且調整單選按鈕(與錨=「W」),而不是居中使他們看起來更乾淨。

from Tkinter import * 
import time 

class App: 
    def __init__(self, master): 
     w = Label(master, text="1. Anxiety, nervousness, worry or fear") 
     w.pack() 

     v = IntVar() 
     Radiobutton(master, text="0 for not at all", variable=v, value=1).pack(side=TOP, anchor="w") 
     Radiobutton(master, text="1 for somewhat", variable=v, value=2).pack(side=TOP, anchor="w") 
     Radiobutton(master, text="2 for moderatly", variable=v, value=3).pack(side=TOP, anchor="w") 
     Radiobutton(master, text="3 for a lot", variable=v, value=4).pack(side=TOP, anchor="w") 

     self.button = Button(master, text="BACK", fg="red", command=self.button6) 
     self.button.pack(side=BOTTOM) 
     self.button = Button(master, text="NEXT", fg="red", command=self.button5) 
     self.button.pack(side=BOTTOM) 

    def button6(self): 
     print "Sam is awesome!GAJONGA" 

    def button5(self): 
     print "PYTHON FOR THE WIN! GIAN SAYS PYTHON = FILTHY" 

master = Tk() 
app = App(master) 
master.mainloop() 
0

master是傳遞給App.__init__()參數;它不存在於此之外,例如您嘗試使用它的全球範圍內。

+0

感謝您發表評論伊格納西奧,但我仍然要多一個小白的:-(明白你的意思。我們的大部分代碼是從互聯網上的例子中剪切和粘貼,我們很快學習到:-D PS STACKOVERFLOW.COM真棒! – gian848396