Search code examples
pythontkinterradio-button

Trying to get value of selected tkinter.radiobutton using .get(), but can't get the selected value


I'm trying to use radio buttons in python for the first time and am having trouble getting the value of the selected radio button. print(test) just prints out "lamp". I already looked through a dozen topics on the same problem but could not find an answer.

tkinter imported as tk

def additionalData(df: DataFrame):
            global dataBox
            dataBox = tk.Tk()
            dataBox.title("Additional data")
            dataBox.geometry("300x375+800+400")
            dataBox.config(bg="lightgray")

            sensorLoc = StringVar(value="lamp")
            lblSensorLoc = tk.Label(dataBox, text="Sensor location:")
            lblSensorLoc.grid(row=3,column=1,pady=25)
            rdSL1 = tk.Radiobutton(dataBox, text="Ankle", variable=sensorLoc, value="Ankle", tristatevalue="x")
            rdSL1.grid(row=3,column=2)
            rdSL2 = tk.Radiobutton(dataBox, text="Foot", variable=sensorLoc, value="Foot", tristatevalue="x")
            rdSL2.grid(row=4,column=2)
            rdSL3 = tk.Radiobutton(dataBox, text="Shank", variable=sensorLoc, value="Shank", tristatevalue="x")
            rdSL3.grid(row=5,column=2, pady=25)

            test = sensorLoc.get()
            btn_save = Button(dataBox, text="SAVE", command=lambda: 
            [   
                print(test)
            ])
            btn_save.grid(row=7,column=2, pady=25)

I cut out most of the function to make it easier to read


Solution

  • test = sensorLoc.get() will set test to 'lamp' and that's it! What you need is to update 'test' dynamically, like this.

    test = sensorLoc.get
    btn_save = tk.Button(dataBox, text="SAVE", command=lambda: [print(test())])
    

    Now when button is pressed the current radiobutton value will be returned.