Button命令参数不起作用

时间:2017-10-07 16:23:24

标签: python python-2.7 button tkinter parameters

我有这个程序的问题,当我按下按钮

时命令不起作用
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()

当程序启动时,按下按钮之前会打印出数字。如果有人知道的话请回答。感谢

1 个答案:

答案 0 :(得分:1)

您需要更改以下行:

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)

对此:

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)

通过使用lambda函数,您可以将所需的变量传递给函数,而无需在开始时调用它。当Tkinter评估您传递的内容为command时,会立即调用它。