gpt4 book ai didi

数学游戏 Tkinter 中的 Python 计时器

转载 作者:太空狗 更新时间:2023-10-30 03:03:57 25 4
gpt4 key购买 nike

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

from Tkinter import *import tkMessageBoximport randomimport timeimport 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 answerdef 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 definitiondef quit():   global root   root.destroy()#Definition for the timer this part doesnt workdef 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 coderoot = Tk()root.title("multiplikations tidtagning")root.geometry('800x500')count_flag = True# Welcome message in labelslabel2 = 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 labelslabel3 = 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 labellabel1 = Label(root)label1.grid(row=2, column=0)# entry widget for the start buttonentry1 = Entry(root)entry1.grid(row=3, column=0)# restart gives a new questionentry1.bind('', func=lambda e:checkAnswer())#ButtonsfragaBtn = 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 timeclass 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com