我厭倦了創建倒數計時器。在計時器持續時間內,用戶應該能夠輸入文本。但是,它只顯示 .after() 期間之后的文本(我認為這至少是正在發生的事情)。它在每個周期后更新,然后顯示文本。有什么解決方法嗎?有沒有其他方法可以創建可以避免此問題的倒數計時器?
import tkinter
from tkinter import *
def showClue(clue):
# Create window
root = tkinter.Tk()
root.state('zoomed')
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
# Frame
clue_frame = tkinter.Frame(root, bg='#0000AF')
clue_frame.pack(expand=True, fill='both')
# Clue label
clue = tkinter.Label(clue_frame, text=clue, bg='#0000AF', fg='white')
clue.config(font=('ITC Korinna Std', 60), wraplength=1250)
# Input
userinput = tkinter.Entry(clue_frame, width=50)
userinput.config(font=('ITC Korinna Std', 25))
# Countdown timer
timer = tkinter.IntVar()
timer.set(15)
time = tkinter.Label(clue_frame,textvariable=timer, bg='#0000AF', fg='white')
time.config(font=('ITC Korinna Std', 50),padx=10,pady=10)
time.pack(anchor='c',expand=True)
clue.pack(anchor= 'c',expand=True)
userinput.pack(anchor='c',expand=True)
timeleft = timer.get()
# Update countdown timer after each second
while timeleft > -1:
root.after(1000)
timer.set(timeleft)
timeleft -= 1
root.update()
root.mainloop()
showClue('test')
我想要這段代碼做的是在用戶輸入文本時顯示文本,而不是在每次更新后才顯示。
uj5u.com熱心網友回復:
root.after 方法用于執行某種回呼,作為時間過去后應執行的操作的第二個引數。要修復只需創建一個每秒更新變數的回呼函式。并在回呼中繼續倒計時。
例如:
import tkinter
from tkinter import *
def countdown(root, timer): # this is the callback function
timeleft = timer.get()
if timeleft > 0:
timer.set(timeleft-1)
root.after(1000, countdown, root, timer) # reschedule callback
def showClue(clue):
# Create window
root = tkinter.Tk()
root.state('zoomed')
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
# Frame
clue_frame = tkinter.Frame(root, bg='#0000AF')
clue_frame.pack(expand=True, fill='both')
# Clue label
clue = tkinter.Label(clue_frame, text=clue, bg='#0000AF', fg='white')
clue.config(font=('ITC Korinna Std', 60), wraplength=1250)
# Input
userinput = tkinter.Entry(clue_frame, width=50)
userinput.config(font=('ITC Korinna Std', 25))
# Countdown timer
timer = tkinter.IntVar()
timer.set(15)
time = tkinter.Label(clue_frame,textvariable=timer, bg='#0000AF', fg='white')
time.config(font=('ITC Korinna Std', 50),padx=10,pady=10)
time.pack(anchor='c',expand=True)
clue.pack(anchor= 'c',expand=True)
userinput.pack(anchor='c',expand=True)
root.after(1000,countdown, root, timer) # start countdown
root.mainloop()
showClue('test')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533600.html
