gian848396 gian848396 - 24 days ago 13
Python Question

Add radio button to Tkinter

My friend and I are working on making a window that displays 4 radio buttons, text and we are struggling to add two buttons on the bottom.

Here is our code:

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()


Running this gives us the following error:

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

Answer

You need to actually initialize the App class in order for it to do anything. The label should go inside the init method along with all the other widgets. Normally you'd put all of the widgets inside the frame (e.g., Radiobutton(frame, text= ...), but if you aren't going to use the frame there's no need to create it. And aligning the radiobuttons (with anchor="w") instead of centering makes them look cleaner.

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()
Comments