按钮命令参数不起作用

2024-09-30 06:18:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,这个程序的命令不工作,当我按下按钮

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()

当程序启动时,在我按下按钮之前会打印数字。如果有人知道什么,请回答。谢谢


Tags: ortextimport程序ifbuttonrandom按钮
1条回答
网友
1楼 · 发布于 2024-09-30 06:18:59

您需要更改以下行:

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进行评估

相关问题 更多 >

    热门问题