gpt4 book ai didi

Python Tkinter 秒表错误

转载 作者:行者123 更新时间:2023-12-01 04:36:43 25 4
gpt4 key购买 nike

我用 python 和 tkinter 制作了一个双倒数计时器,但如果 tkinter 窗口不在前台并且不能同时运行,它似乎无法运行。这是我的代码:

import tkinter as tk
import tkinter.ttk as ttk
import time
class app:

def __init__(self):
self = 0

def mainGUIArea():
def count_down_1():
for i in range(79, -1, -1):
timeCount = "{:02d}:{:02d}".format(*divmod(i, 60))
time_str.set(timeCount)
root.update()
time.sleep(1)

def count_down_2():
for j in range(10, -1, -1):
timeCount = "{:02d}:{:02d}".format(*divmod(j, 60))
time_str1.set(timeCount)
root.update()
time.sleep(1)

#Main Window
root = tk.Tk()
root.title("Super Timer V1.0")
root.minsize(300,300)
root.geometry("500x300")

#Timer1
time_str = tk.StringVar()
label_font = ('Courier New', 40)
tk.Label(root, textvariable = time_str, font = label_font, bg = 'white', fg = 'blue', relief = 'raised', bd=3).pack(fill='x', padx=5, pady=5)
tk.Button(root, text=' Start Timer! ',bg='lightgreen',fg='black', command=count_down_1).pack()
tk.Button(root, text='Stop and Exit',bg='red',fg='white', command=root.destroy).pack()

#Timer2
time_str1 = tk.StringVar()
label_font = ('Courier New', 40)
tk.Label(root, textvariable = time_str1, font = label_font, bg = 'white', fg='blue', relief='raised', bd=3).pack(fill='x', padx=5, pady=5)
tk.Button(root, text=' Start Timer! ',bg='lightblue',fg='black', command=count_down_2).pack()
tk.Button(root, text='Stop and Exit',bg='red',fg='white', command=root.destroy).pack()


def main():
app.mainGUIArea()

main()

你有什么建议吗?谢谢:)

最佳答案

time.sleep 的调用至少是问题的一部分。当你调用 sleep 时,它实际上就是这样做的——它让应用程序进入休眠状态。无法处理任何事件并且 GUI 卡住。这是倒计时器的错误方法。

另一个问题是循环内对 update 的调用以及对 time.sleep 的调用。此调用将处理事件,这意味着当其中一个循环正在运行并且您单击按钮时,您可能最终会调用另一个函数,从而交错两个循环。

定期执行某些操作的正确方法是使用 after 重复调用函数。一般模式是这样的:

def update_display(self):
<do whatever code you want to update the display>
root.after(1000, self.update_display)

您可以让任意数量的并行运行(显然,达到实际限制),并且您的 GUI 将在更新之间完全响应。

这是一个简单的示例:

class Countdown(tk.Label):
def __init__(self, parent):
tk.Label.__init__(self, parent, width=5, text="00:00")
self.value = 0
self._job_id = None

def tick(self):
self.value -= 1
text = "{:02d}:{:02d}".format(*divmod(self.value, 60))
self.configure(text=text)
if self.value > 0:
self._job_id = self.after(1000, self.tick)

def start(self, starting_value=60):
if self._job_id is not None: return

self.value = starting_value
self.stop_requested = False
self.after(1000, self.tick)

def stop(self):
self.after_cancel(self._job_id)
self._job_id = None

关于Python Tkinter 秒表错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31585464/

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