首页 > 解决方案 > Python - 给时间在输入中输入答案

问题描述

我使用 tkinter 创建了一个 GUI,并希望执行以下操作:

  1. 播放录音
  2. 激活并关注输入
  3. 等待一段时间播放新录音并重新开始

我想让用户听到录音,让他输入他听到的内容,然后继续循环。我也尝试过使用my_gui.after(),time.sleep()my_gui.update(),但我无法弄清楚。

我的代码如下所示:

from tkinter import *

my_gui = Tk()

for i in range(0,10):
    play_sound(file)
    entry = Entry(my_gui).pack()
    my_gui.update()
    entry.focus()
    my_gui.after(3000,None)

my_gui.mainloop()

当我运行代码时很难输入一些文本。

标签: loopstime

解决方案


我不确定这是否是你要找的,但看看这个例子:

from tkinter import *
import winsound

my_gui = Tk()

my_entries = [] # to append all the entries, so theyr not useless afterwards
counter = 0 #to index the list of entries and give focus to it
tot_entries_num = 9 #total number of entries to be created 

def new():
    global counter
    if counter < tot_entries_num: # if total number of entries are not created
        winsound.PlaySound('Systemhand',winsound.SND_ASYNC) #play a sound or any thing, replace with what you want, but you might need threading.
        my_entries(Entry(my_gui)) #appending an entry to the list
        my_entries[counter].pack() #calling the current item from the list and then pack() on it
        my_entries[counter].insert(0,counter+1) #not necessary, just if you want to see the number of the entries created, remove the +1 to see the entries with index number

        my_entries[counter].focus_force() #get the current item created from the list and give focus to it
        counter += 1 #increase the counter number by 1
        
    rep = my_gui.after(3000,new) # repeat the function for every 3 seconds
    
    if counter > tot_entries_num: #if total number of entries created
        my_gui.after_cancel(rep) # then stop repeating 

new() #call the function initially

my_gui.mainloop()

我已经评论了这个例子,让它在旅途中更容易理解。此外,如果您想get()在条目上使用 ,您会说,所需的条目号从 0 开始my_entries[n].get()在哪里。n


推荐阅读