tkinter radiobutton is not giving a return

Question:

I’m wondering why my radiobutton variable is not returning a value. Kindly see my setup below :

Global declarations of the frame, radiobuttons, template variable and ‘Download’ button. I placed my radiobuttons in a frame. I commented the set() function here.

root = tk.Tk()
frm_radioButtons = tk.Frame(root)
template = tk.StringVar()
# template.set("m")
rbtn_create_delete = tk.Radiobutton(frm_radioButtons, text="Create/Delete items", font=(
    'Arial', 8), variable="template", value="cd")

rbtn_move = tk.Radiobutton(
    frm_radioButtons, text="Move items", font=('Arial', 8), variable="template", value="m")

btn_download = tk.Button(frm_radioButtons, text="Download",
                         font=('Arial', 7), command=generate_template, padx=15)

And created them inside a function below. Tried using global keyword but still not working. This is the main point of entry of this script.

def load_gui():
    root.geometry("300x360")

    frm_radioButtons.columnconfigure(0, weight=1)
    frm_radioButtons.columnconfigure(1, weight=1)

    #global rbtn_create_delete
    #global rbtn_move
    rbtn_move.grid(row=0, column=0)
    rbtn_create_delete.grid(row=0, column=1)
    btn_download.grid(row=1, column=0)
    frm_radioButtons.pack(padx=10, anchor='w')

And here is the generate_template function when the ‘Download’ button is clicked. Note though, that the "Move items" radiobutton is pre-selected when I run the program even if I set(None).

It doesn’t print anything.

def generate_template():
    type = template.get()
    print(type)

Tried a pretty straightforward code below and still did not work. It returns empty string. Switched to IntVar() with 1 & 2 as values, but only returns 0.

import tkinter as tk


def download():
    print(btnVar.get())


root = tk.Tk()
btnVar = tk.StringVar()
rbtn1 = tk.Radiobutton(root, text="Button1", variable="bntVar", value="b1")
rbtn2 = tk.Radiobutton(root, text="Button1", variable="bntVar", value="b2")
rbtn1.pack()
rbtn2.pack()
btn_dl = tk.Button(root, text="Download", command=download)
btn_dl.pack()
root.mainloop()

Been reading here for the same issues but I haven’t got the correct solution. Appreciate any help. tnx in advance..

Expected result: get() function return

Asked By: la_mun

||

Answers:

The value passed to the variable option needs to be a tkinter variable. You’re passing it a string.

In the bottom example it needs to be like this:

rbtn1 = tk.Radiobutton(root, text="Button1", variable=btnVar, value="b1")
rbtn2 = tk.Radiobutton(root, text="Button1", variable=btnVar, value="b2")
#                                                     ^^^^^^
Answered By: Bryan Oakley
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.