我試圖在 python 中制作一個秒表,但每次由于溢位而停止作業時,有人可以解決這個問題嗎?
代碼:
import time
from tkinter import *
cur=time.time()
root = Tk()
def functio():
while True:
s = time.time()-cur
l1 = Label(root,text=s)
l1.pack()
l1.destroy()
time.sleep(0.5)
Button(root,text='Start',command=functio).pack()
root.mainloop()
uj5u.com熱心網友回復:
執行流程永遠不會退出你的無限回圈。它會無休止地阻塞 UI,因為執行流程永遠不會回傳到 tkinter 的主回圈。
您需要將“functio”函式更改為:
def functio():
s = time.time()-cur
l1 = Label(root,text=s)
l1.pack()
l1.destroy()
root.after(500, functio)
話雖如此,我不確定這個功能是否有意義:您創建一個小部件,然后立即銷毀它?
uj5u.com熱心網友回復:
你會想要做這樣的事情:
import time
from tkinter import *
root = Tk()
def functio():
global timerStarted
global cur
# check if we started the timer already and
# start it if we didn't
if not timerStarted:
cur = time.time()
timerStarted = True
s = round(time.time()-cur, 1)
# config text of the label
l1.config(text=s)
# use after() instead of sleep() like Paul already noted
root.after(500, functio)
timerStarted = False
Button(root, text='Start', command=functio).pack()
l1 = Label(root, text='0')
l1.pack()
root.mainloop()
uj5u.com熱心網友回復:
while 回圈將阻止 tkintermainloop處理掛起的事件,請after()改用。
此外,最好在函式外創建標簽并在函式內更新它:
import time
# avoid using wildcard import
import tkinter as tk
cur = time.time()
root = tk.Tk()
def functio():
# update label text
l1['text'] = round(time.time()-cur, 4)
# use after() instead of while loop and time.sleep()
l1.after(500, functio)
tk.Button(root, text='Start', command=functio).pack()
# create the label first
l1 = tk.Label(root)
l1.pack()
root.mainloop()
請注意,不建議使用通配符匯入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/365760.html
上一篇:如何將影像放入函式定義中?
