tkinter Radiobuttons not displaying value in class

Viewed 42

I'm currently a college student learning python and am stuck with some Radiobutton issues using tkinter. When using multiple classes my radiobuttons won't update their values and will always print out the .set() method's value. This is a snippet of code similar to what I have in my lab but its just the problem area.

import matplotlib
matplotlib.use("TkAgg")
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
from matplotlib.figure import Figure


class test(tk.Tk):
    def __init__(self):
        super().__init__()
        self.TOPNUM=15


class dialogWindow(test):
    def __init__(self):
        super().__init__()

        self.rc=tk.IntVar()
        self.rc.set(20)


        self.radio1=tk.Radiobutton(self,text="1",value=1,variable=self.rc,command=self.rc.get())
        self.radio2=tk.Radiobutton(self,text="2",value=2,variable=self.rc,command=self.rc.get())

        self.button=tk.Button(self,text="CLick Me!",command=lambda : self.clicked(self.rc.get()))

        self.radio1.pack()
        self.radio2.pack()
        self.button.pack()
        self.rc.set(20)

    def clicked(self,value):
        print(value)


def run():
    win=test()
    win.title("Top Colleges")
    win.minsize(200,200)
    header=tk.Label(win,text="College Lookup",fg="blue",font=15)
    header.pack()

    dataButton=tk.Button(win,text="By Data",width=8, command= lambda : dialogWindow())

    dataButton.pack()

    win.mainloop()

run()

However, when I tried writing it in just a single class instead it does work and I can't figure out why.

class dialogWindow(tk.Tk):
    def __init__(self):
        super().__init__()

        self.rc=tk.IntVar()
        self.rc.set(20)

        self.radio1=tk.Radiobutton(self,text="1",value="1",variable=self.rc,command=self.rc.get())
        self.radio2=tk.Radiobutton(self,text="2",value="2",variable=self.rc,command=self.rc.get())

        self.button=tk.Button(self,text="CLick Me!",command=lambda : self.clicked(self.rc.get()))

        self.radio1.pack()
        self.radio2.pack()
        self.button.pack()
        self.rc.set(1)

    def clicked(self,value):
        print(value)


def run():
    win=dialogWindow()
    win.minsize(200,200)
    dataButton=tk.Button(win,text="By Data",width=8, command= lambda:dialogWindow())

    dataButton.grid(row=1,column=2,padx=5)

    win.mainloop()
run()
1 Answers

The explanation is quite simple, there is two instances of Tk() created because of inheritance. Now you have to specify which instance the IntVar() should belong to, because it always sets itself to the first created instance(win), but here you don't want that. So:

class dialogWindow(test):
    def __init__(self):
        super().__init__()
        
        self.rc=tk.IntVar(self)
        .....
Related