简体   繁体   中英

Python tkinter Radio Button Won't Change Variable

I'm trying to use radio buttons in python 3.4.3 and the radio buttons are not changing their assigned variable. What am I missing here?

from tkinter import *
import tkinter

class c:
def __init__(self):
    self.master=tkinter.Tk()
    self.bvar=IntVar()
    rb1=Radiobutton(self.master,text="1",variable= self.bvar,value=1,command=self.rbselect).pack()
    rb2=Radiobutton(self.master,text="0",variable=self.bvar,value=0,command=self.rbselect).pack()

def rbselect(self):
    print(self.bvar)

def run(self):
    self.master.mainloop()

app=c()
app.run()

If by "not changing their assigned variable", you mean "it always prints PY_VAR0 no matter which one I select", yes, that is normal behavior - printing an IntVar doesn't give you any information regarding what value it contains. Try using get instead.

def rbselect(self):
    print(self.bvar.get())

Now choosing the "1" radio button causes "1" to be printed, and likewise for "0".

Need to use .get() to compare IntVar instances:

from tkinter import *
import tkinter

class c:
    def __init__(self):
        self.master=tkinter.Tk()
        self.b=IntVar() 
        rb1=Radiobutton(self.master,text="1",variable= self.b,value=1,command=self.rbselect).pack()
        rb2=Radiobutton(self.master,text="0",variable= self.b,value=0,command=self.rbselect).pack()

    def rbselect(self):
        print(self.b.get())

    def run(self):
        self.master.mainloop()

app=c()
app.run()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM