简体   繁体   中英

Radiobutton not working properly in python

I am working on python gui in tkinter and trying for a unit converter. Initially when I took my cursor at lower radio buttons they are automatically selected, please anyone help me how can I get rid of this.

from Tkinter import *
import tkMessageBox

root=Tk()
root.wm_title("Measurement Converter")

def Distance():

    def sel():
        print var.get()  

    L1 = Label(root, text="Enter Value :",font=20)
    L1.grid(row=3,column=0,padx=(0,10),columnspan=2)
    E1=Entry(root,justify=CENTER,width=20).grid(row=3,column=1,padx=(0,0),ipady=10,ipadx=20)
    L2 = Label(root, text="units in-")
    L2.grid(row=4,column=1,padx=(0,0))
    var = IntVar()
    R1 = Radiobutton(root, text="Meter", variable=var, value=1,command=sel)
    R1.grid(row=4,column=1,padx=(120,0))
    R2 = Radiobutton(root, text="Km", variable=var, value=2,command=sel)
    R2.grid(row=4,column=1,padx=(240,0))
    R3 = Radiobutton(root, text="Feet", variable=var, value=3,command=sel)
    R3.grid(row=4,column=1,columnspan=2,padx=(100,0),pady=4) 

    L3 = Label(root, text="convert into-")
    L3.grid(row=5,column=1,padx=(0,0))
    var3 = IntVar()
    RB1 = Radiobutton(root, text="Meter", variable=var3, value=1,command=sel)
    RB1.grid(row=5,column=1,padx=(120,0))
    RB2 = Radiobutton(root, text="Km", variable=var3, value=2,command=sel)
    RB2.grid(row=5,column=1,padx=(240,0))
    RB3 = Radiobutton(root, text="Feet", variable=var3, value=3,command=sel)
    RB3.grid(row=5,column=1,columnspan=2,padx=(100,0),pady=5) 

label1=Label(root, text='Select any Button to convert it in other Unit',bg="green",fg="white",justify=CENTER,borderwidth=1,font=20,padx=20 )
label1.grid(pady=15,padx=(15,15),row=0,column=1)

buttontext1=StringVar()
button1=Button(root,textvariable=buttontext1,font=25,padx=5,pady=5,width=15,command=Distance,bg='#FF0000')
buttontext1.set("Distance")
button1.grid(row=1,column=0,padx=(100,00))

buttontext2=StringVar()
button2=Button(root,textvariable=buttontext2,font=25,padx=5,pady=5,width=15,command=Distance,bg='#66FF66')
buttontext2.set("Weight")
button2.grid(row=1,column=2,padx=(0,100))

buttontext3=StringVar()
button3=Button(root,textvariable=buttontext3,font=25,padx=5,pady=5,width=15,command=Distance,bg='#3399CC')
buttontext3.set("Temprature")
button3.grid(row=2,column=0,pady=50,padx=(100,0))

buttontext4=StringVar()
button4=Button(root,textvariable=buttontext4,font=25,padx=5,pady=5,width=15,command=Distance,bg='#CCFF00')
buttontext4.set("Volume")
button4.grid(row=2,column=2,padx=(0,100))


root.mainloop()

I had few time so I developed this quickly. It's just a starting point, and surely it can be enhanced. I prefered to develop as class so you could separate elaboration code from display code (you should just develop another class and instantiate it inside Gui's calc method). When you have to do the conversion you have to query self.radio"variable" to get user selected option. If you need further help, please ask. I'll try to answer as soon as possible.

from Tkinter import *

class Calculate:
    def __init__(self):
        self.stuff = None #store here cosstants to do conversions...
    def convert1(self,startval):#,someother params to specify "from" and "to"):
        return startval#this is an identity just as example
    def convert2(self,startval):
        pass
    #...and so on...
class Gui:
    def __init__(self):
        self.root = Tk()
        self.c = Calculate()
        self.volumef = StringVar()
        self.volumef.set("C")
        self.volumet = StringVar()
        self.volumet.set("C")
        self.weightf = StringVar()
        self.weightf.set("K")
        self.weightt = StringVar()
        self.weightt.set("K")
        self.distancef = StringVar()
        self.distancef.set("M")
        self.distancet = StringVar()
        self.distancet.set("M")
        self.temperaturef = StringVar()
        self.temperaturef.set("C")
        self.temperaturet = StringVar()
        self.temperaturet.set("C")
        self.f3 = None
        self.f4 = None
        self.f5 = None
        self.DISTANCEMODES = [("Meter", "M"),
                              ("Km", "K"),
                              ("Feet", "F")       
                             ]
        self.VOLUMEMODES = [ ("cm^3","C"),
                             ("m^3","M"),
                             ("mm^3","MM")
                           ]
        self.TEMPERATUREMODE = [ ("Celsius","C"),
                                 ("Farenheit","H"),
                                 ("Kelvin","K")
                               ]
        self.WEIGHTMODE = [ ("Kg","K"),
                            ("g","G"),
                            ("mg","M")
                          ]
        self.root.title("Conversions")
        self.f1 = Frame(self.root,relief=SUNKEN)
        self.f1.pack()
        self.createWidgets()
        self.root.mainloop()


    def createWidgets(self):
        self.f1 = Frame(self.root)
        self.bd = Button(self.f1, text="Distance",command=self.distance,width=10)
        self.bd.pack(side=LEFT,padx=10,pady=10)

        self.bw = Button(self.f1, text="Weight",command=self.weight,width=10)
        self.bw.pack(side=LEFT,padx=10,pady=10)

        self.f1.pack()
        self.f2 = Frame(self.root)
        self.bt = Button(self.f2, text="Temperature",command=self.temperature,width=10)
        self.bt.pack(side=LEFT,padx=10,pady=10)

        self.bv = Button(self.f2, text="Volume",command=self.volume,width=10)
        self.bv.pack(side=LEFT,padx=10,pady=10)
        self.f2.pack()

    def convert(self,val):
        var = self.edit1.get()#get value

        if val==0:#choose what conversion applay
            #x = self.c.convert1(var,self.volumef,self.volumet)
            x = self.c.convert1(var)#do a conversion
            print "volume calc"
        elif val==1:
            x = self.c.convert1(var)#do a conversion
            print "weight calc"
        elif val==2:
            x = self.c.convert1(var)#do a conversion
            print "distance calc"
        elif val==3:
            x = self.c.convert1(var)#do a conversion
            print "temperature calc"           
        else:
            print "it should never happen, but u can trow an excepion"
            x=0 #to avoid a python s.f. as I don't trow/manage exceptions


        self.edit2.config(state=NORMAL)#set as normal to be able to edit
        self.edit2.delete(0,END)#delete previous content 
        self.edit2.insert(0,x)#add new content
        self.edit2.config(state=DISABLED)#do not allow user input
    def createRadio(self,fv,tv,cmdp,mode):#fromvariable,tovariable,commandparam,mode
        if self.f3 and self.f4 and self.f5:
            self.f3.pack_forget()
            self.f4.pack_forget()
            self.f5.pack_forget()
        #FROM:
        self.f3 = Frame(self.root)
        lbl = Label(self.f3,text="From:",width=8)
        lbl.pack(side=LEFT)
        for m_text,m_mode in mode:
            b = Radiobutton(self.f3,text=m_text,value=m_mode,variable=fv)
            b.pack(side=LEFT)
        self.edit1 = Entry(self.f3,width=10)
        self.edit1.pack(side=LEFT)
        self.f3.pack()
        #TO:
        self.f4 = Frame(self.root)
        lbl = Label(self.f4,text="To:",width=8)
        lbl.pack(side=LEFT)
        for m_text,m_mode in mode:
            b = Radiobutton(self.f4,text=m_text,value=m_mode,variable=tv)
            b.pack(side=LEFT)
        self.edit2 = Entry(self.f4,width=10)
        self.edit2.config(state=DISABLED)        
        self.edit2.pack(side=LEFT)
        self.f4.pack()
        self.f5 = Frame(self.root)
        self.btnCalc = Button(self.f5,text="Calc",command=lambda:self.convert(cmdp),width=10)
        self.btnCalc.pack()
        self.f5.pack()


    def volume(self):
        self.createRadio(self.volumef,self.volumet,0,self.VOLUMEMODES)

    def weight(self):
        self.createRadio(self.weightf,self.weightt,1,self.WEIGHTMODE)

    def distance(self):
        self.createRadio(self.distancef,self.distancet,2,self.DISTANCEMODES)

    def temperature(self):
        self.createRadio(self.temperaturef,self.temperaturet,3,self.TEMPERATUREMODE)

Gui()

[EDIT]: ok i fixed a bit my code, now it should have a bit more sense ;)

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