K
K
Keesti2020-05-16 22:10:42
Python
Keesti, 2020-05-16 22:10:42

Why does the function fire when the program starts, but does not work on further calls?

I am studying the graphical interface, I decided to write a small program (it doesn’t really matter what it was supposed to do), but I ran into such a problem.
The check function is triggered when the program starts, but is not called when the button is clicked, which should have called it. I can't figure out what the problem is.
Thanks in advance.

Program text:

from tkinter import *

class App:

    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.answer1 = Button(
            frame, text="2", command=self.check(2)
        )
        self.answer1.pack()

        self.lable = Label(
            master, text='''Сколько будет 2+2?
            Пожалуйста, введите ответ(только цифры)''',
            bg="black", fg="white"
        )
        self.lable.pack()

        self.button = Button(
            frame, text="Выход", command=frame.quit
        )
        self.button.pack()

    def check(self, x=int):
        if x != 4:
            print("Ответ ", x, " неверен")
        else:
            print("Верно")

root = Tk()
root.geometry('600x420')
app = App(root)

root.mainloop()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-05-16
@Keesti

because there should be a function name and you have a call to it.
The name is self.check
and the call is self.check(2)
so it is called when the button is created and since it doesn't return anything None is assigned to the command - pressing the button with command=None does nothing.
You'll want to know how to fix it:
you can use a one-line (lambda) function

self.answer1 = Button(
            frame, text="2", command=lambda: self.check(2)
        )

lambda: self.check(2) - will return a pointer to a function that will call self.check with argument 2 when called without any arguments, and return the result of self.check(2) if it would be needed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question