Flavio Oliveira
Flavio Oliveira

Reputation: 419

Tkinter packge for python, how return the chosen option?

I'm learning about tkinter and would like to use it in my project, but I'm stuck on how to do this. I would like to know how the code returns the chosen option.

Here is the code:

from tkinter import *
from tkinter.ttk import *

master = Tk()
master.geometry("175x200")

v = StringVar(master, "1")

options = {
          "RadioButton 1": "1",
          "RadioButton 2": "2",
          "RadioButton 3": "3",
          "RadioButton 4": "4",
          "RadioButton 5": "5"
}

for (text, value) in options.items():
    Radiobutton(master, text=text, variable=v,
                value=value).pack(side=TOP, ipady=5)

print(StringVar())

quit_btn = Button(master, text="Quit", command=master.quit, width=10)
quit_btn.pack()

mainloop()

def selected_opition():
    return options.get(text, value)

print(selected_opition())

Upvotes: 0

Views: 69

Answers (1)

Jem
Jem

Reputation: 567

Although there were some more small mistakes, the main point was to only call v.get() after a button is pressed. So you'd have to put it in a function, as I did with the quitbutton() function. That function will be called as soon as the button is clicked as it says command=quitbutton.

Also, you tried printing the StringVar() but you shouldn't do that. You created a variable v which is the StringVar. After that, you should call that v instead of StringVar. So instead of doing print(StringVar), you should print(v.get())

I also recommend you to watch some tutorials on Youtube about Tkinter as this will enhance your understanding of the basic principles. You're code was pretty good but it missed some of the basics which made it not work in the way you wanted it to.

from tkinter import *
from tkinter.ttk import *

master = Tk()
master.geometry("175x200")

# Changed this do StringVar() without anything in it and set the beginning value to 1
v = StringVar(master)
v.set(1)

options = {
          "RadioButton 1": "1",
          "RadioButton 2": "2",
          "RadioButton 3": "3",
          "RadioButton 4": "4",
          "RadioButton 5": "5"
}

for (text, value) in options.items():
    Radiobutton(master, text=text, variable=v,
                value=value).pack(side=TOP, ipady=5)

# Created a function that runs every time the button gets clicked (see the command=quitbutton in the Button widget) and gets the value of the button that is selected
def quitbutton():
    print(v.get())
    # master.quit() uncomment this line if you want to close the window after clicking the button


# Changed the function which gets called by changing the word after command=
quit_btn = Button(master, text="Quit", command=quitbutton, width=10)
quit_btn.pack()

mainloop()

Upvotes: 2

Related Questions