Tkinter按钮不执行命令

时间:2018-07-11 08:39:41

标签: python python-2.7 button tkinter

我正在尝试为“危险”创建一个计数器,以便我和妈妈都能保持得分。当前,我正在创建的程序正在将值分配给变量,然后在我按下窗口中的按钮时不执行命令。我正在运行Python 2.7.13。     将Tkinter导入为tk

root = tk.Tk()
root.title("Jeopardy Scores")

def ChangeScore(User,Value):
    if User == 1:
         Score = int(JScore.get())
         JScore.set(Score + Value)
         #J = JScore.get()
         #print J
         #SayHi()

    else:
         Score = int(MScore.get())
         MScore.set(Score + Value)
         #M = MScore.get()
         #print M
         #SayHi()

#def SayHi(*args):
    #print 'hi'

MainFrame = tk.Frame(root)
MainFrame.grid(column=0, row=0)
MainFrame.columnconfigure(0, weight=1)
MainFrame.rowconfigure(0, weight=1)

JScore = tk.StringVar()
MScore = tk.StringVar()
JScore.set(0)
MScore.set(0)


JL = tk.Label(MainFrame, text = "Joey's Score", padx = 10, pady = 2)
JL.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
JL.grid(column = 0, row = 0)
ML = tk.Label(MainFrame, text = "Mom's Score", padx = 10, pady = 2)
ML.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
ML.grid(column = 1, row = 0)



JSS = tk.Label(MainFrame, textvariable=JScore ,padx = 122)
JSS.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
JSS.grid(column = 0, row = 1)

MSS = tk.Label(MainFrame, textvariable = MScore,padx = 122)
MSS.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
MSS.grid(column = 1, row = 1)


for i in range(1,6):
    Score = tk.IntVar()
    Score.set(i*200)
    Score1 = 200*i
    JButton = tk.Button(MainFrame, textvariable = Score, command = 
                        ChangeScore(1,Score1))
    JButton.grid(column = 0, row = 1+i)
    MButton = tk.Button(MainFrame, textvariable = Score, command = 
                        ChangeScore(2,Score1))
    MButton.grid(column = 1, row = 1+i)

JButton = tk.Button(MainFrame, text = '400', command = ChangeScore(1,400))
JButton.grid(column = 0, row = 7)


root.mainloop()

代码运行并生成此窗口

请注意,拍摄照片时未按下任何按钮。看起来在代码运行时所有按钮都被“按下了”,然后当我随后按下按钮时什么也没发生。

除了可以使我做到这一点的小信息之外,我没有使用Tkinter的经验,并且我对Python有更多的经验。我主要是为自己做练习,以提高自己的编码效率,并最终将其用于“危险!”。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

这里@Configuration的{​​{1}}参数应该是可调用的。您不应该自己调用函数并将返回值传递给它。相反,您提供了一个稍后要调用的函数。

因此将您的代码更改为类似

command

创建一个lambda以便稍后调用将解决此问题。