Home > Back-end >  How do I make this Tkinter Radiobutton in Python only add the letter that's been selected once,
How do I make this Tkinter Radiobutton in Python only add the letter that's been selected once,

Time:07-25

I am trying to make a Python app with GUI using Tkinter that would allow user to select a letter from a choice of two letters, then the letter that's selected right before the user closes the tab to be added to the array selectedletter and printed.

from tkinter import *

def addletter():
    a = "a"
    b = "b"
    if(x.get()==0):
        selectedletter.append(a)
    if(x.get()==1):
        selectedletter.append(b)


window = Tk()

letters = ["a", "b"]
selectedletter = []

x= IntVar()
for index in range(len(letters)):
        radiobutton = Radiobutton(window,
                                  text=letters[index],
                                  value=index,
                                  variable=x,
                                  command=addletter()
                                  )
        radiobutton.pack()

window.mainloop()

print(selectedletter)

However for some reason, instead of only adding the letter that's selected to the array, it only adds the first letter (in this case a) two times. For example when the letter that's selected before the closing the program is b, I would want the output to be ['b'], but instead what I get is ['a', 'a']. How do I get the desired output?

CodePudding user response:

Take off the brackets from the command=addletter after that it should work.

Here is an explanation.

from tkinter import *

def addletter():
    a = "a"
    b = "b"
    if(x.get()==0):
        selectedletter.append(a)
    if(x.get()==1):
        selectedletter.append(b)
    print(selectedletter)


window = Tk()

letters = ["a", "b"]
selectedletter = []

x= IntVar()
for index in range(len(letters)):
        radiobutton = Radiobutton(window,
                                  text=letters[index],
                                  value=index,
                                  variable=x,
                                  command=addletter
                                  )
        radiobutton.pack()

window.mainloop()

print(selectedletter)
  • Related