2017-10-07 99 views
-1

我有這個程序有問題的命令不工作時,我按下按鈕按鈕命令參數不工作

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

您需要更改下面幾行:

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

+0

非常感謝,現在完美! – MattZ