按钮命令参数不工作
问题描述:
我有这个程序有问题的命令不工作时,我按下按钮按钮命令参数不工作
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()
发生的事情是,打印张数之前,我按下按钮,当程序开始。如果有人知道,请回答。由于
答
您需要更改下面几行:
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
。
非常感谢,现在完美! – MattZ