Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tkinter Radiobutton variable output

I'm trying to find a way to take the value from a Radiobutton, set it to a variable, and use the variable outside the class in other parts of my code. Heres a sample of my code:

from Tkinter import *

class Window():

    def __init__(self, master):

        self.master = master
        self.v1 = IntVar()

        Label(master, text="""Which Method?""",justify = LEFT, padx = 20).pack()
        Radiobutton(master, text="Positive",padx = 20, variable=self.v1, value=1).pack(anchor=W)
        Radiobutton(master, text="Negative", padx = 20, variable=self.v1, value=2).pack(anchor=W)
        Radiobutton(master, text="Both", padx = 20, variable=self.v1, value=3).pack(anchor=W)

Is there a way, preferably without use definitions and the command option, to set a variable "Method" to the value that the user selected? And then use that value outside the class.

I tried using Method=self.v1.get() but that didn't work.

like image 394
Jeremy G Avatar asked Apr 09 '26 10:04

Jeremy G


1 Answers

from Tkinter import *

class Window():

    def __init__(self, master):

        self.master = master
        self.v1 = IntVar()

        Label(master, text="""Which Method?""",justify = LEFT, padx = 20).pack()
        Radiobutton(master, text="Positive",padx = 20, variable=self.v1, value=1).pack(anchor=W)
        Radiobutton(master, text="Negative", padx = 20, variable=self.v1, value=2).pack(anchor=W)
        Radiobutton(master, text="Both", padx = 20, variable=self.v1, value=3).pack(anchor=W)

root = Tk()
w = Window(root)
w.master.mainloop()

print "The radiobutton outside of the class: %d" %w.v1.get()

Here is an example of what I mean in my comment. My example should print the value of whichever Radiobutton is currently selected when you close the window.

In your case, depending on whichever value the Radiobutton has, you would decide which functions to call.

like image 81
maccartm Avatar answered Apr 11 '26 03:04

maccartm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!