The Labels on my window don't appear when the correct button is pressed

Question:

I have a quiz that I made in python (Tkinter). For some reason, when I press a button, I doesn’t show the label. I have no more info about this, because it does not even give me an error message.

here is the (bad) code:

from random import *

def submit():
    ca = 0
    ca = randint(1, 3)
    if ca == 1:
        if val1 == 1:
            score = Label(winroot, text="1 is Correct")
            score.pack()  
    if ca == 2:
        if val2 == 1:
            score = Label(winroot, text="2 is Correct")
            score.pack()
    if ca == 3:
        if val3 == 1:
            score = Label(winroot, text="3 is Correct")
            score.pack()
                    
win = Tk()
win.title("ziqp Quiz")
    
winroot = Frame(win)
winroot.pack()
    
question = Label(winroot, width=60, font=(10), text="Q")
question.pack()
    
val1 = IntVar()
val2 = IntVar()
val3 = IntVar()
    
option1 = Checkbutton(winroot, variable=val1, text="1", command=submit)
option1.pack()
    
option2 = Checkbutton(winroot, variable=val2, text="2", command=submit)
option2.pack()
    
option3 = Checkbutton(winroot, variable=val3, text="3", command=submit)
option3.pack()
    
nextb = Button(winroot, text="Submit", command=submit)
nextb.pack()
    
    
    
win.mainloop()
Asked By: zonellobster

||

Answers:

Your code is incomplete.
But the first thing that jumps out at me is that you have:

val1 = IntVar()

and in

def submit():

you’re checking if:

if val1 == 1:

But val1 is an IntVar Tkinter variable, which you would check with:

val1.get()

In your code, your conditionals always fail, because val1 will never be equal to 1, because it’s an IntVar

So, remember, with an IntVar (and all the other Tkinter variables), you assign with .set() and check with .get(), so…

val2.set(1)
if val2.get() == 1:
    print("Nice! They're equal!")

Addendum: in your case, since you’re using the IntVars as variables for the Checkbuttons, the system is handling the "setting" of the values for the IntVars. But you still need to read their values using the .get() method.

Answered By: GaryMBloom
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.