t用“下一步”按钮重复此过程

2024-09-30 03:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想建立一个简单的tkinter, GUI将显示文本,用户需要读取文本并保存音频。我的代码目前工作,但进程不可重复,我的目标用户按下“下一步”按钮时,进程将重复进程。。。当用户按下“结束”按钮时,进程将停止。 有什么办法吗

 import sounddevice as sd 
  import soundfile as sf 
  from tkinter import *
  
def Voice_rec(): 
    fs = 48000
      
    # seconds 
    duration = 5
    myrecording = sd.rec(int(duration * fs),  
                         samplerate=fs, channels=2) 
    sd.wait() 
      
   
    return sf.write('save_audio.wav', myrecording, fs) 
  
master = Tk() 
import os, random
txtfile = random.choice(os.listdir(""))
txtread = "" + txtfile
with open(txtread, "r") as filek:
    textfile=filek.read()
#     Label(master, text=filek.read()).pack()  
wrapper = LabelFrame(master,text="sound record")
wrapper.pack(fill="both",expand="yes",padx=20,pady=20)


lbl3 = Label(wrapper,text=textfile,borderwidth=2, relief="solid",bg = "red")
lbl3.config(font=("Courier", 20))
lbl3.pack()  
    
#def next():
#    import os, random
#    txtfile = random.choice(os.listdir("path"))
#    txtread = "path" + txtfile
#    with open(txtread, "r") as filek:
#        textfile=filek.read()
    #     Label(master, text=filek.read()).pack()  
#    wrapper = LabelFrame(master,text="sound record")
#    wrapper.pack(fill="both",padx=20,pady=20)
#    lbl3 = Label(wrapper,text=textfile,borderwidth=2, relief="solid",bg = "red")
#    lbl3.config(font=("Courier", 20))
#    lbl3.pack()  
    
    
Label(wrapper, text=" Voice Recoder : "
     )#.grid(row=0, sticky=W, rowspan=5) 
  
b = Button(wrapper, text="Start", command=Voice_rec) 
b.pack()


c = Button(wrapper, text="Next", command=next) 
c.pack()
#b.grid(row=0, column=2, columnspan=2, rowspan=2, 
 #      padx=5, pady=5) 
    
mainloop()

上面的代码我从这个链接中引用:https://www.geeksforgeeks.org/build-a-voice-recorder-gui-using-python/


Tags: textimportmaster进程osasrandomwrapper
1条回答
网友
1楼 · 发布于 2024-09-30 03:22:22

我建议您将其包装在函数中:

txtfile = random.choice(os.listdir(""))
txtread = "" + txtfile
with open(txtread, "r") as filek:
    textfile = filek.read()

然后可以链接到Next按钮,每次加载一个新文件。不要每次都重新呈现整个UI

换句话说,类似这样的事情:

master = Tk()
text_file = StringVar()
wrapper = LabelFrame(master, text="sound record")
wrapper.pack(fill="both", expand="yes", padx=20, pady=20)
lbl3 = Label(wrapper)


def next_audio():
    path = "path/"
    txtfile = random.choice(os.listdir(path))
    txtread = os.join(path, txtfile)
    with open(txtread, "r") as filek:
        text_file.set(filek.read())
    print(text_file.get())
    lbl3.configure(text=text_file.get())


next_audio()
lbl3.configure(text=text_file.get(), borderwidth=2, relief="solid", bg="red")
lbl3.config(font=("Courier", 20))
lbl3.pack()

这不是最好看的代码,但这并不是我的初衷,只是尝试使用你的代码来表达我的意思。也可能是关于Tkinter的提示,而不是使用grid几何体管理器pack和{}不是现代Tkinter的最佳实践

希望这有帮助

相关问题 更多 >

    热门问题