关于用户界面:数学游戏Tkinter中的Python计时器

Python timer in math game Tkinter

我想为我的简单数学游戏添加一个计时器。到目前为止,一切都很好,用户在按下按钮时会收到问题,并得到答案的反馈。我想为用户添加一个计时器,以查看回答乘法需要多少时间。这是我的数学游戏原型的最后一部分。我希望计时器在用户单击"nyt tal"时启动,这在瑞典语中表示新的数字,在用户单击"svar"时停止,这在瑞典语中表示应答。这是我的密码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from Tkinter import *
import tkMessageBox
import random
import time
import sys

# Definition for the question asked to user
def fraga1():
    global num3
    num3 = random.randint(1, 10)
    global num4
    num4 = random.randint(1, 10)
    global svar1
    svar1 = num3 * num4
    label1.config(text='Vad blir ' + str(num3) + '*' + str(num4) + '?')
    entry1.focus_set()


#The answer giving feedback based on answer
def svar1():
   mainAnswer = entry1.get()
   if len(mainAnswer) == 0:
      tkMessageBox.showwarning(message='Skriv in n?gra nummer!')
   return
   if int(mainAnswer) != svar1:
      tkMessageBox.showwarning(message='Tyv?rr det r?tta svaret: ' + str(svar1))
   else:
      tkMessageBox.showinfo(message='R?TT!! :)')

#The quit button definition
def quit():
   global root
   root.destroy()

#Definition for the timer this part doesnt work
def start():
   global count_flag
   fraga1()
   count_flag = True
   count = 0.0
   while True:
      if count_flag == False:
          break
   label['text'] = str(count)
   time.sleep(0.1)
   root.update()
   count += 0.1


#Window code
root = Tk()
root.title("multiplikations tidtagning")
root.geometry('800x500')

count_flag = True

# Welcome message in labels
label2 = Label(root, text="Hej!
  Nu ska vi l?sa lite matteproblem!"
)
label2.config(font=('times', 18, 'bold'), fg='black', bg='white')
label2.grid(row=0, column=0)

#Instructions how to play in labels

label3 = Label(root, text="Instruktioner!
  F?r att starta ett spel tryck p? nyttspel"
)
label3.config(font=('times', 12, 'bold'), fg='black', bg='white')
label3.grid(row=2, column=2)

#other label
label1 = Label(root)
label1.grid(row=2, column=0)


# entry widget for the start button
entry1 = Entry(root)
entry1.grid(row=3, column=0)

# restart gives a new question
entry1.bind('', func=lambda e:checkAnswer())

#Buttons

fragaBtn = Button(root, text='Nytt tal', command=fraga1)
fragaBtn.grid(row=4, column=0)

svarButton = Button(root, text='Svar', command=svar1)
svarButton.grid(row=4, column=1)


quit_bttn = Button(root, text ="Avsluta", command=quit)
quit_bttn.grid(row=5, column=0)



root.mainloop()


我想你需要的是这个。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from Tkinter import *
import time

class StopWatch(Frame):  
   """ Implements a stop watch frame widget."""                                                                
    def __init__(self, parent=None, **kw):        
        Frame.__init__(self, parent, kw)
        self._start = 0.0        
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()              
        self.makeWidgets()      

    def makeWidgets(self):                        
       """ Make the time label."""
        l = Label(self, textvariable=self.timestr)
        self._setTime(self._elapsedtime)
        l.pack(fill=X, expand=NO, pady=2, padx=2)                      

    def _update(self):
       """ Update the label with elapsed time."""
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._timer = self.after(50, self._update)

    def _setTime(self, elap):
       """ Set the time string to Minutes:Seconds:Hundreths"""
        minutes = int(elap/60)
        seconds = int(elap - minutes*60.0)
        hseconds = int((elap - minutes*60.0 - seconds)*100)                
        self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))

    def Start(self):                                                    
       """ Start the stopwatch, ignore if running."""
        if not self._running:            
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1        

    def Stop(self):                                    
       """ Stop the stopwatch, ignore if stopped."""
        if self._running:
            self.after_cancel(self._timer)            
            self._elapsedtime = time.time() - self._start    
            self._setTime(self._elapsedtime)
            self._running = 0

    def Reset(self):                                  
       """ Reset the stopwatch."""
        self._start = time.time()        
        self._elapsedtime = 0.0    
        self._setTime(self._elapsedtime)


def main():
    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)

    Button(root, text='Start', command=sw.Start).pack(side=LEFT)
    Button(root, text='Stop', command=sw.Stop).pack(side=LEFT)
    Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
    Button(root, text='Quit', command=root.quit).pack(side=LEFT)

    root.mainloop()

if __name__ == '__main__':
    main()

P.S:把它应用到代码中,我刚刚在Tkinter中实现了基本计时器。


使用一个全局变量来存储人员按下"开始"时的当前时间。然后,当用户在函数svar中按下svar时,只需获取当前时间,将它们彼此相减,就可以得到所用的时间,然后将全局var重置为0,voila,就可以得到所用的时间。


我想你可以用"after"。创建一个小部件…

1
2
3
4
5
6
7
8
9
10
time = 60 #60 seconds for example
widget = Tkinter.Label().pack()

def count():
    global time
    if time > 0:
       time -= 1
       widget.config(text="Time left:" + str(time))

       widget.after(1000, count)

我使用Python 3X对不起的