如何计算按下按钮的数字并打印屏幕上按下的总数

时间:2016-06-07 13:14:20

标签: python button tkinter

from tkinter import *
app = Tk()
app.title("quiz")
app.geometry('300x100+200+100')
b1 = Button(app, text = "correct!", width = 10,
            command = play_correct)
b1.pack(side ='left', padx = 10, pady = 10)
b2 = Button(app, text = "wrong!", width = 10,
            command = play_wrong)
b2.pack(side ='right', padx = 10, pady = 10)

当我在shell上键入number_asked时,我该怎么做 我得到了正确和错误按钮的总数; 当我输入number_correct时,我得到的总数我按下“正确!”按钮; 当我输入number_wrong时,我得到了我按下“错误!”的总数。按钮。

1 个答案:

答案 0 :(得分:1)

您需要定义一个回调并将其绑定到您的按钮

b1 = Button(app, text = "correct!", width = 10,
            command = play_correct)
b1.pack(side ='left', padx = 10, pady = 10)
b2 = Button(app, text = "wrong!", width = 10,
            command = play_wrong)
b2.pack(side ='right', padx = 10, pady = 10)

def play_correct():
    self.num_correct += 1

def play_wrong():
    self.num_wrong += 1

此外,您可以在外部绑定回调

b1 = Button(app, text = "correct!", width = 10,
            command = play_correct)
b1.pack(side ='left', padx = 10, pady = 10)
b2 = Button(app, text = "wrong!", width = 10,
            command = play_wrong)
b2.pack(side ='right', padx = 10, pady = 10)

def play_correct():
    self.num_correct += 1

def play_wrong():
    self.num_wrong += 1

b1.bind("<Button-1>", onCorrect)

b2.bind("<Button-1>", onNotCorrect)