0

I'm trying to do a simple program using python but it doesn't work. In the penultimate string I don't know how to get the variable from the Radiobutton.

from tkinter import*
import tkinter.messagebox

finestra = Tk()
finestra.geometry("1000x800+100+0")
finestra.title("Consumo PC")
var = IntVar()
ivar = IntVar()
cpu = Label(text="Seleziona la generazione del tuo processore:").pack()
kaby = Radiobutton(finestra,text="Kabylake",value=1, variable=var).pack()
sky = Radiobutton(finestra,text="SkyLake",value=2, variable=var).pack()
ivy = Radiobutton(finestra,text="IvyBridge",value=3, variable=var).pack()

serie = Label(text="Seleziona il tuo processore:").pack()
i3 = Radiobutton(finestra,text="i3 xxxx",value=6, variable=ivar).pack()
i5 = Radiobutton(finestra,text="i5 xxxx",value=4, variable=ivar).pack()
i7 = Radiobutton(finestra,text="i7 xxxx",value=5, variable=ivar).pack()

brand = Label(text="Seleziona il brand della tua scheda video:").pack()
amd = Radiobutton(finestra,text="AMD", value=7,variable=3).pack()
nvidia = Radiobutton(finestra,text="Nvidia", value=8,variable=3).pack()

kaby = 1
sky = 1
ivy = 11/10
i3 = 51
i5 = 65
i7 = 75

tdp = Label(text=var.get()+ivar.get()).pack()


finestra.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685

1 Answers1

1

Right now, you are changing text of label only as soon as you create your UI and since none of those selected, you are getting 0. That text should update on every var/ivar change.

That can be achieved by adding trace for var and ivar.

def callback(*args):
    print(var.get()+ivar.get())

var.trace("w", callback)
ivar.trace("w", callback)

With this, on every button selection, you will get your desired value.

Now one thing left, which is updating the resul label. There are couple ways to update the text of label but since we are using variable classes, let's do it using StringVar.

def callback(*args):
    result.set(var.get()+ivar.get())

result = StringVar()

tdp = Label(textvariable=result).pack()
                ^^^^^^^^ note that this not text but textvariable!     

Also, there are couple things you should be aware.

One of them is wildcard import (from tkinter import * usage).
About this one, you can read answers from this question.

Other one is, using pack() at the same line. That will assign None to all of your variables(cpu, kaby, sky etc.).
About this one, you can read answers from this question.

Lafexlos
  • 7,618
  • 5
  • 38
  • 53
  • I did as you said. But the addends are the values written in the Radio-Button row. As you can note I wanted to add the same values to Kaby and Sky. How can I do this? I'm still using from tkinter import owing to I don't know what I have to write under - import tkinter -. –  Jul 05 '17 at 19:40
  • @T.Sala I don't think, I understand what you wanted but overall, if you want to do something when var/ivar change, you need to do it in `callback`. – Lafexlos Jul 06 '17 at 11:27