0

I am trying to assign a value to a variable using a radio button in python with the following code:

def print_me():
global payment
global membership

if studentMemString == "PY_VAR0":
    membership = "STUDENT"
    payment = studentMem
elif adultMemString == "PY_VAR10":
    membership = "ADULT"
    payment = adultMem
elif childMemString == "PY_VAR0":
    membership = "CHILD"
    payment = childMem
else:
    pass
print(membership)
print(payment)


root = tk.Tk()
studentMem = tk.StringVar()
studentMemString = str(studentMem)

adultMem = tk.StringVar()
adultMemString = str(adultMem)

childMem = tk.StringVar()
childMemString = str(childMem)


studentRadBtn = tk.Radiobutton(root, text="Student - £19.99", 
variable=studentMem, value= 19.99)
studentRadBtn.pack()
adultRadBtn = tk.Radiobutton(root, text="Adult - £34.99", variable=adultMem, 
value= 34.99)
adultRadBtn.pack()
childRadBtn = tk.Radiobutton(root, text="Child - £5.99", variable=childMem, 
value=5.99)
childRadBtn.pack()

button = tk.Button(root, text="click", command=print_me)
button.pack()

root.mainloop()

(update) Okay So now the issue is that when i start the program all the radio buttons are active and regardless of which one I try to click on the only one that is called is the first one. Why are they all selected?

Cameron Hamilton
  • 29
  • 1
  • 2
  • 8

1 Answers1

0

In the below code radiobuttons change the value of a variable v when selected. The initial value of v is "2", so the 2nd radiobutton is selected by default.

import tkinter as tk

root = tk.Tk()

v = tk.StringVar()
v.set("2")

tk.Label(root, textvariable=v).pack()

tk.Radiobutton(root, text="one", variable=v, value="1").pack()
tk.Radiobutton(root, text="two", variable=v, value="2").pack()
tk.Radiobutton(root, text="three", variable=v, value="3").pack()

root.mainloop()
Nae
  • 14,209
  • 7
  • 52
  • 79
  • Okay so according to this each radio button will return 'PY_VAR0' right? How would I change the value of another variable according to the actual variable of 'v'. For instance depending on which radio button is selected variable 'x' equals 'y'. and do this for each rad button – Cameron Hamilton Nov 30 '17 at 18:33
  • @CameronHamilton No in this example `v.get()` will return 1, 2, 3 etc. – Nae Nov 30 '17 at 18:34
  • ahhhh okay thankyou so there is no need to convert the string var into a string in my example code – Cameron Hamilton Nov 30 '17 at 18:36
  • @CameronHamilton You will need to use `v.get()` when you want that variable to manipulate other stuff. So there can be a need. – Nae Nov 30 '17 at 18:57