-1

i have a problem with this program the command does not work when i press the button

from Tkinter import *
import random
MenuP = Tk()
MenuP.geometry("540x960")

def Respuesta1(a):
    if a == 1:
        resp = random.randint(0,4)
        if resp == 0:
            r = 3
        elif resp == 1 or resp == 2:
            r = 5
        else:
            r = 7
    if a == 2:
        resp = random.randint(0,4)
        if resp == 0:
            r = 1
        elif resp == 3 or resp == 2:
            r = 5
        else:
            r = 3
    print r

C1 = Button(MenuP, text = "1", command = Respuesta1(1)).place(x = 100,y = 100)
C2 = Button(MenuP, text = "2", command = Respuesta1(2)).place(x = 300,y = 100)
MenuP.mainloop()

what happens is that the number prints before i press the button, when the program starts. If someone knows something please answer. Thanks

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
MattZ
  • 19
  • 4

1 Answers1

1

You need to change the following lines:

C1 = Button(MenuP, text = "1", command = Respuesta1(1)).place(x = 100,y = 100)
C2 = Button(MenuP, text = "2", command = Respuesta1(2)).place(x = 300,y = 100)

To this:

C1 = Button(MenuP, text = "1", command = lambda: Respuesta1(1))
C1.place(x = 100,y = 100)
C2 = Button(MenuP, text = "2", command = lambda: Respuesta1(2))
C2.place(x = 300,y = 100)

By using a lambda function you can pass the desired variable to the function, without calling it at the start. It is called straight away as Tkinter evaluates the contents of what you pass as command.

SneakyTurtle
  • 1,831
  • 1
  • 13
  • 23