Reputation: 51
I am trying to make a simple app in Tkinter but I ran into a problem. I am trying to use the value that is defined with a Radio Button in a function, but it doesn't seem to work. When I press the Button nothing is printed. What am I doing wrong?
from tkinter import *
window = Tk()
window.title("ALL YOU NEED IS EXCEL")
window.geometry('500x200')
variable_1 = StringVar()
rad1 = Radiobutton(window,text='Button 1', value= "Button 1", variable= variable_1)
rad1.grid(column=0, row=4)
rad2 = Radiobutton(window,text='Button 2', value= "Button 2",variable= variable_1)
rad2.grid(column=1, row=4)
def clicked(vrijednost):
if vrijednost == "Button 1":
print("This is Button 1")
if vrijednost == "Button 2":
print("This is Button 2")
btn = Button(window, text="PRINT", height = 2,width = 15, command=clicked(variable_1))
#btn.grid(column=1, row=5)
btn.place(x = 250, y = 150)
window.mainloop()
Upvotes: 1
Views: 149
Reputation: 4543
Edit: Adding StringVar()
parameter.
However, using walrus operator this can be done quite easily. code:
from tkinter import *
window = Tk()
window.title("ALL YOU NEED IS EXCEL")
window.geometry('500x200')
variable_1 = StringVar(window, '1')
rad1 = Radiobutton(window,text='Button 1', value= "Button 1", variable= variable_1)
rad1.grid(column=0, row=4)
rad2 = Radiobutton(window,text='Button 2', value= "Button 2",variable= variable_1)
rad2.grid(column=1, row=4)
def clicked():
if (vrijednost := variable_1.get()) == "Button 1":
print("This is Button 1")
else:
print("This is Button 2")
btn = Button(window, text="PRINT", height = 2,width = 15, command=clicked)
btn.place(x = 250, y = 150)
window.mainloop()
Output image:
Output radiobutton2
Upvotes: 0
Reputation: 142
Instead of passing the value in the function, you can use vrijednost = variable_1.get()
inside the function body itself.
Try the following code:
from tkinter import *
window = Tk()
window.title("ALL YOU NEED IS EXCEL")
window.geometry('500x200')
variable_1 = StringVar()
rad1 = Radiobutton(window,text='Button 1', value= "Button 1", variable= variable_1)
rad1.grid(column=0, row=4)
rad2 = Radiobutton(window,text='Button 2', value= "Button 2",variable= variable_1)
rad2.grid(column=1, row=4)
def clicked():
vrijednost = variable_1.get()
if vrijednost == "Button 1":
print("This is Button 1")
if vrijednost == "Button 2":
print("This is Button 2")
btn = Button(window, text="PRINT", height = 2,width = 15, command=clicked)
#btn.grid(column=1, row=5)
btn.place(x = 250, y = 150)
window.mainloop()
Upvotes: 1