数学游戏 Tkinter 中的 Python 计时器

标签 python user-interface python-2.7 timer tkinter

我想为我的简单数学游戏添加一个计时器。到目前为止,一切正常,用户在按下按钮时会收到问题,并会收到有关答案的反馈。我想为用户添加一个计时器,以查看回答乘法需要多长时间。这是我这个数学游戏原型(prototype)的最后一部分。我希望计时器在用户单击“nytt tal”时启动,这意味着瑞典语中的新数字,并在用户单击“svar”时停止计时器,这意味着在瑞典语中回答。这是我的代码。

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!\n  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!\n  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()

最佳答案

我想你需要的是这个。

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 中实现了基本计时器。

关于数学游戏 Tkinter 中的 Python 计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17569007/

相关文章:

asp.net-mvc - asp.net mvc - 完全脱离 DB 中的自定义字段构建 View

android - 为简单的塞尔达风格冒险游戏选择 2D 游戏引擎

python - 制作一个名称只有在程序运行后才知道的列表

python - 如何使用 python 以编程方式计算存档中的文件数

python - 检查一个数字是否只有 2 个数字的组合

python - 模型的输出张量必须是 Keras `Layer` 的输出(从而保存过去层的元数据)。当使用 CNN LSTM 的函数式 api 时

user-interface - 使用 ZeroMQ 进行跨平台开发?

python - 读取存储在文本文件中的列表

python - 如何知道 cronjob 是否失败(运行 python 命令)

python - 使用 Python 的二进制分数模式