在Tkinter中添加单选按钮

1 投票
2 回答
8925 浏览
提问于 2025-04-17 04:21

我和我的朋友正在制作一个窗口,这个窗口里有4个单选按钮和一些文字,但我们在底部添加两个按钮时遇到了困难。

这是我们的代码:

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

2 个回答

0

master 是传递给 App.__init__() 的一个参数;在全局范围内,比如你尝试使用它的地方,它并不存在。

3

你需要先初始化App类,这样它才能开始工作。标签应该放在初始化方法里面,和其他所有的控件一起。通常情况下,你会把所有的控件放在一个框架里面(比如,Radiobutton(frame, text= ...),但如果你不打算使用这个框架,就没必要创建它。而且,把单选按钮对齐(使用anchor="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()

撰写回答