简体   繁体   中英

How to print countdown timer and accept user input at the same time (python)?

Clarificaition

This is a repost of my previous question as I am extremely desperate to receive an answer to my problem. I am quite new and if this is against any of the rules, please inform me as I would remove this post if so.

I want to create a quiz-like program where the user would be able to see the countdown timer ticking down every second while they can input their answer at any time. According to my previous post regarding this question, I've tried using threading in my code. Here is a sample of my code.

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: ")

It does function, but the problem is that the user input is forced to return back (\r) while the timer doesn't properly remove the '0' of the 10 which is not what I desire. Here is the output:

不需要的输出

It would be a tremendous help if you could suggest a solution to this problem. Thank you in advance.

After some messing around, I came up with this. If you would like me to edit this to make it work without the windows, let me know.

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()

Hope this helps, and you're welcome.乇卩丨匚卄乂尺 (To stop the window from being fullscreen, change the (window).attributes('-fullscreen', True) to (window).geometry(500x500) or whatever you wish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM