Skip to content Skip to sidebar Skip to footer

How To Handle A Click Button Event In Python Module Tkinter

I am trying to make a question game in python using tkinter. I am struggling to define a function that can check the answer that the player clicked on and add to a score that is th

Solution 1:

Starting at the top, let's change your check_answer definition to not create a new label every time:

def check_answer(answer):
    ifanswer== answers[s][0] oranswer== answers[s][1]:
        global score
        score += 1
        lbl["text"] = score

Next, we need one small change in your for loop: we want to send answer, not i:

for i in output:
    answer = tkinter.Button(window, text=i, command=lambda answer = i: check_answer(answer))
    answer.pack()

lbl = tkinter.Label(window, text=score)
lbl.pack()

Lastly, we'll add that label that we removed earlier down to the bottom where you had it initially. You can change the location of this by packing it sooner in the code for aesthetics. Your code still doesn't cycle to a new question once one is answered (correctly or otherwise), but at least now you can see when the user answers correctly.

Hope this helps.

Solution 2:

First of all, you did a small error in the lambda callback:

command=lambda answer=i: check_answer(answer)

It should be.

Then for the many labels, create one label and just change the text:

defcheck_answer(answer):
    print(answer)
    if answer == answers[s][0] or answer == answers[s][1]:
        global score
        score += 1
    lbl.configure(text=str(score))

(much code i did not copy)

for i in output:
    answer = tkinter.Button(window, text=i, command=lambda answer=i: check_answer(answer))
    answer.pack()

lbl = tkinter.Label(window, text=score)
lbl.pack()

Post a Comment for "How To Handle A Click Button Event In Python Module Tkinter"