0

I am trying to use a function to update a variable from a radio button selection using:

from tkinter import *

root = Tk()

var1 = StringVar(value = 'rb0')
var2 = StringVar(value = 'rb0')

def fnc1(x):
    var2.set(x)
    return

Radiobutton(root, text = 'rb1', variable = var1, value = 'rb1', command = fnc1('rb1')).pack()
Radiobutton(root, text = 'rb2', variable = var1, value = 'rb2', command = fnc1('rb2')).pack()
Radiobutton(root, text = 'rb3', variable = var1, value = 'rb3', command = fnc1('rb3')).pack()

Label(root, textvariable = var1).pack()
Label(root, textvariable = var2).pack()

root.mainloop()

The first label works fine using the normal method however the second label (var2) always shows 'rb3' even on opening the code for the first time (when no button is even checked?).

How can I get the code to update the second variable along with the first one?

KGoed
  • 27
  • 3

1 Answers1

1

Tkinter thingys basically don't like inputs into functions so you have to use a lambda.

Update your code to this:

from tkinter import *

root = Tk()

var1 = StringVar(value = 'rb0')
var2 = StringVar(value = 'rb0')

def fnc1(x):
    var2.set(x)
    return

Radiobutton(root, text = 'rb1', variable = var1, value = 'rb1', command = lambda: fnc1('rb1')).pack()
Radiobutton(root, text = 'rb2', variable = var1, value = 'rb2', command = lambda: fnc1('rb2')).pack()
Radiobutton(root, text = 'rb3', variable = var1, value = 'rb3', command = lambda: fnc1('rb3')).pack()

Label(root, textvariable = var1).pack()
Label(root, textvariable = var2).pack()

root.mainloop()
Caleb Mackle
  • 120
  • 1
  • 6