Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tkinter button command runs function without clicking? [duplicate]

im brand new to GUIs and python itself really. im trying to make a simple triva game in python 3.x using tkinter. the idea is that it will have multiple questions and will tell you if you got it right or wrong as well as tell you how many you got right. the issue im running into however, is that for some reason all the buttons i have act as if they have been clicked when they havent. code below:

from tkinter import *
class Correct(object):
    value = True
    def __init__(self, text):
        self.text = text


class Incorrect(object):
    value = False
    def __init__(self, text):
        self.text = text


def check(value):
    if value == True:
        print("you picked the right answer!")
    else:
        print("sorry thats not right")


question1 = ["this is a question", Correct("right answer"), Incorrect("wrong b"), Incorrect("wrong c"),
             Incorrect("wrong d")]


master = Tk()

qlabel1 = Label(master,text=question1[0])

# buttons
choice1 = Button(master, text=question1[1].text, command=check(question1[1].value))
choice2 = Button(master, text=question1[2].text, command=check(question1[2].value))
choice3 = Button(master, text=question1[3].text, command=check(question1[3].value))
choice4 = Button(master, text=question1[4].text, command=check(question1[3].value))

# pack
qlabel1.grid(row=0, column=0)
choice1.grid(row=1, column=0)
choice2.grid(row=1, column=2)
choice3.grid(row=2, column=0)
choice4.grid(row=2, column=1)
mainloop()
like image 566
vinnie Avatar asked Dec 25 '22 19:12

vinnie


1 Answers

choice1 = Button(master, text=question1[1].text, command=lambda : check(question1[1].value))

After command, you must give a function (either defined with def before or with lambda on the spot).

like image 56
Eric Levieil Avatar answered Dec 27 '22 12:12

Eric Levieil