![](/img/trans.png)
[英]How do you display a countdown timer and accept user input at the same time (python)?
[英]How to print countdown timer and accept user input at the same time (python)?
澄清
這是我之前問題的轉貼,因為我非常渴望收到我的問題的答案。 我是新手,如果這違反了任何規則,請通知我,如果是的話我會刪除這篇文章。
我想創建一個類似測驗的程序,用戶可以在其中看到倒數計時器每秒滴答作響,同時他們可以隨時輸入答案。 根據我之前關於這個問題的帖子,我嘗試在我的代碼中使用線程。 這是我的代碼示例。
from threading import Thread
import time
import sys
def func1():
t = 10
for t in range (t,1,-1):
sys.stdout.write('\r' + str(t))
sys.stdout.flush()
time.sleep(1)
if __name__ == '__main__':
Thread(target = func1).start()
answer = input("\tEnter: ")
它確實是 function,但問題是用戶輸入被迫返回 (\r),而計時器沒有正確刪除 10 的“0”,這不是我想要的。 這是 output:
如果您能提出解決此問題的建議,那將是一個巨大的幫助。 先感謝您。
經過一番折騰,我想到了這個。 如果您希望我編輯它以使其在沒有 windows 的情況下工作,請告訴我。
import time
import tkinter
from tkinter import messagebox
from tkinter import *
from tkinter import ttk
from threading import Thread
def clear():
print('\033[H\033[J', end='')
run = True
def timer():
tim = int(input("Type how long the countdown should last in seconds: "))
clear()
count = 0
while count < tim and run == True:
clear()
b1 = (tim-count)
c = (str(b1),"second(s) left")
win = Tk()
win = Tk()
win.attributes('-fullscreen', True)
if run == False:
win.destroy()
Label(win, text= c,
font=('Helvetica 20 bold')).pack(pady=20)
win.after(1000,lambda:win.destroy())
win.mainloop()
time.sleep(1)
count += 1
def take_input():
inpu = input()
#Your code
def time_input():
global run
while run == True:
t1 = Thread(target=timer)
t2 = Thread(target=take_input)
t1.start()
t2.start()
t2.join()
thread_running = False
run = False
time_input()
希望這會有所幫助,不客氣。尤嬰丨齊占尺(要阻止 window 全屏顯示,請將 (window).attributes('-fullscreen', True) 更改為 (window).geometry(500x500) 或您想要的任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.