import os import random import time from fnmatch import fnmatch import pygame import tkinter as tk root = tk.Tk() root.geometry("450x200+374+182") root.title("英语单词") english1 = "" def word(): while 1: path = "D:\MY python\English" lists = os.listdir(path) english = (random.choice(lists)) global english1 english1 = english.strip(".mp3") print(english1) time.sleep(3) basedir = r"D:\MY python\English" for root, dirs, files in os.walk(basedir): for file in files: english3 = os.path.join(root, file) if fnmatch(file, f"{english1}*.mp3"): pygame.mixer.init() pygame.mixer.music.load(english3) pygame.mixer.music.play() time.sleep(3) button = tk.Button(root, text="开始", command=word) button.grid(row=0, column=0) w = tk.Label(root, text=f"{english1}") w.grid(row=1, column=0) root.mainloop()
时间: 2024-04-10 07:29:27 浏览: 131
这段代码是一个简单的英语单词学习程序。它使用了`os`、`random`、`time`、`fnmatch`、`pygame`和`tkinter`库。通过点击"开始"按钮,程序会从指定路径中随机选择一个英语单词的音频文件,并播放出来。同时,程序会将选择的单词显示在窗口上方的标签中。
需要注意的是,这段代码中使用了硬编码的路径,如果你想要运行该程序,需要根据你自己的文件路径进行相应的修改。
相关问题
import os import random import time from fnmatch import fnmatch import pygame import tkinter as tk from tkinter import * import wave import threading import tkinter import tkinter.filedialog import tkinter.messagebox import pyaudio from urllib import request, parse import json root = tk.Tk() root.geometry("450x250+374+182") root.title("英语单词") english1 = "开始" res = "中文翻译" w = Message(root, font=('times', 15, 'bold'), text=english1) w.pack() timer_running = False a = Message(root, font=('times', 15, 'bold'), text=res) a.pack() def wands(): w.after(2000, word) time.sleep(3) w.after(2000, speak) def word(): path = "D:\MY python\English" lists = os.listdir(path) english = (random.choice(lists)) global english1 english1 = english[:-4] w.configure(text=f"{english1}") res = fy(f"{english1}") a.configure(text=f"{res}") def speak(): basedir = r"D:\MY python\English" for root, dirs, files in os.walk(basedir): for file in files: english3 = os.path.join(root, file) if fnmatch(file, f"{english1}*.wav"): pygame.mixer.init() pygame.mixer.music.load(english3) pygame.mixer.music.play() wands() 添加一个停止按钮
可以使用tkinter库来添加一个停止按钮。下面是修改后的代码:
```python
import os
import random
import time
from fnmatch import fnmatch
import pygame
import tkinter as tk
from tkinter import *
import wave
import threading
import tkinter
import tkinter.filedialog
import tkinter.messagebox
import pyaudio
from urllib import request, parse
import json
root = tk.Tk()
root.geometry("450x250+374+182")
root.title("英语单词")
english1 = "开始"
res = "中文翻译"
w = Message(root, font=('times', 15, 'bold'), text=english1)
w.pack()
timer_running = False
a = Message(root, font=('times', 15, 'bold'), text=res)
a.pack()
def wands():
w.after(2000, word)
time.sleep(3)
w.after(2000, speak)
def word():
path = "D:\MY python\English"
lists = os.listdir(path)
english = (random.choice(lists))
global english1
english1 = english[:-4]
w.configure(text=f"{english1}")
res = fy(f"{english1}")
a.configure(text=f"{res}")
def speak():
basedir = r"D:\MY python\English"
for root, dirs, files in os.walk(basedir):
for file in files:
english3 = os.path.join(root, file)
if fnmatch(file, f"{english1}*.wav"):
pygame.mixer.init()
pygame.mixer.music.load(english3)
pygame.mixer.music.play()
wands()
def stop_speak():
pygame.mixer.music.stop()
def fy(english):
content = english
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
data = {}
data['i'] = content
data['from'] = 'AUTO'
data['to'] = 'AUTO'
data['smartresult'] = 'dict'
data['client'] = 'fanyideskweb'
data['salt'] = '16245570821515'
data['sign'] = '0f4c0f7c60570f9d9b8b62b9b7e3e65f'
data['lts'] = '1624557082151'
data['bv'] = 'e9df4b2b6a5c5a4fdec4a4d3c3e3e7ca'
data['doctype'] = 'json'
data['version'] = '2.1'
data['keyfrom'] = 'fanyi.web'
data['action'] = 'FY_BY_CLICKBUTTION'
data['typoResult'] = 'false'
data = parse.urlencode(data).encode('utf-8')
response = request.urlopen(url, data)
html = response.read().decode('utf-8')
target = json.loads(html)
return target['translateResult'][0][0]['tgt']
stop_button = Button(root, text="停止", command=stop_speak)
stop_button.pack()
wands()
root.mainloop()
```
import os import random import time from fnmatch import fnmatch import pygame import tkinter as tk from tkinter import * import wave import threading import tkinter import tkinter.filedialog import tkinter.messagebox import pyaudio root = tk.Tk() root.geometry("450x200+374+182") root.title("英语单词") english1 = "开始" w = Label(root, font=('times', 20, 'bold'), text=english1) w.pack() timer_running = False def word(): path = "D:\MY python\English" lists = os.listdir(path) english = (random.choice(lists)) global english1 english1 = english.strip(".wav") time.sleep(3) basedir = r"D:\MY python\English" for root, dirs, files in os.walk(basedir): for file in files: english3 = os.path.join(root, file) if fnmatch(file, f"{english1}*.wav"): pygame.mixer.init() pygame.mixer.music.load(english3) pygame.mixer.music.play() w.configure(text=f"{english1}") w.after(100, word) fileName = None allowRecording = False CHUNK_SIZE = 1024 CHANNELS = 2 FORMAT = pyaudio.paInt16 RATE = 44100 def record(): global fileName p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK_SIZE) wf = wave.open(fileName, 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) while allowRecording: data = stream.read(CHUNK_SIZE) wf.writeframes(data) wf.close() stream.stop_stream() stream.close() p.terminate() fileName = None def start(): global allowRecording, fileName fileName = tkinter.filedialog.asksaveasfilename(filetypes=[('未压缩波形文件', '*.wav')]) if not fileName: return if not fileName.endswith('.wav'): fileName = fileName + '.wav' allowRecording = True start_timer() lbStatus['text'] = '正在录音中...' threading.Thread(target=record).start() def stop(): global allowRecording allowRecording = False lbStatus['text'] = '录音已结束' stop_timer() def closeWindow(): if allowRecording: tkinter.messagebox.showerror('Recording', 'Please stop recording before close the window.') return root.destroy() def tick(): global sec sec += 1 time['text'] = sec # Take advantage of the after method of the Label if timer_running: time.after(1000, tick) def start_timer(): global timer_running timer_running = True tick() def stop_timer(): global timer_running, sec timer_running = False sec = 0 time['text'] = sec button = tk.Button(text="开始", command=word) button.pack() btnStart = tkinter.Button(root, text='开始录音', command=start) btnStart.pack() btnStop = tkinter.Button(root, text='结束录音', command=stop) btnStop.pack() lbStatus = tkinter.Label(root, text='录音已准备', anchor='w', fg='green') lbStatus.pack() root.protocol('WM_DELETE_WINDOW', closeWindow) time = Label(root, fg='green') time.pack() root.mainloop()
要实现点击按钮退出并重置时间,可以在按钮的命令函数中添加退出和重置时间的功能。以下是修改的代码示例:
```python
import os
import random
import time
from fnmatch import fnmatch
import pygame
import tkinter as tk
from tkinter import *
import wave
import threading
import tkinter
import tkinter.filedialog
import tkinter.messagebox
import pyaudio
root = tk.Tk()
root.geometry("450x200+374+182")
root.title("英语单词")
english1 = "开始"
w = Label(root, font=('times', 20, 'bold'), text=english1)
w.pack()
timer_running = False
def word():
path = "D:\MY python\English"
lists = os.listdir(path)
english = (random.choice(lists))
global english1
english1 = english.strip(".wav")
time.sleep(3)
basedir = r"D:\MY python\English"
for root, dirs, files in os.walk(basedir):
for file in files:
english3 = os.path.join(root, file)
if fnmatch(file, f"{english1}*.wav"):
pygame.mixer.init()
pygame.mixer.music.load(english3)
pygame.mixer.music.play()
w.configure(text=f"{english1}")
w.after(100, word)
fileName = None
allowRecording = False
CHUNK_SIZE = 1024
CHANNELS = 2
FORMAT = pyaudio.paInt16
RATE = 44100
def record():
global fileName
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK_SIZE)
wf = wave.open(fileName, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
while allowRecording:
data = stream.read(CHUNK_SIZE)
wf.writeframes(data)
wf.close()
stream.stop_stream()
stream.close()
p.terminate()
fileName = None
def start():
global allowRecording, fileName
fileName = tkinter.filedialog.asksaveasfilename(filetypes=[('未压缩波形文件', '*.wav')])
if not fileName:
return
if not fileName.endswith('.wav'):
fileName = fileName + '.wav'
allowRecording = True
start_timer()
lbStatus['text'] = '正在录音中...'
threading.Thread(target=record).start()
def stop():
global allowRecording
allowRecording = False
lbStatus['text'] = '录音已结束'
stop_timer()
def closeWindow():
if allowRecording:
tkinter.messagebox.showerror('Recording', 'Please stop recording before close the window.')
return
stop_timer() # 停止计时器
root.destroy()
def tick():
global sec
sec += 1
time['text'] = sec
# Take advantage of the after method of the Label
if timer_running:
time.after(1000, tick)
def start_timer():
global timer_running, sec
sec = 0 # 重置时间
timer_running = True
tick()
def stop_timer():
global timer_running, sec
timer_running = False
sec = 0
time['text'] = sec
button = tk.Button(text="开始", command=word)
button.pack()
btnStart = tkinter.Button(root, text='开始录音', command=start)
btnStart.pack()
btnStop = tkinter.Button(root, text='结束录音', command=stop)
btnStop.pack()
lbStatus = tkinter.Label(root, text='录音已准备', anchor='w', fg='green')
lbStatus.pack()
root.protocol('WM_DELETE_WINDOW', closeWindow)
time = Label(root, fg='green')
time.pack()
root.mainloop()
```
在上面的代码中,我添加了一个 `stop_timer` 函数来停止计时器并重置时间。在 `stop` 函数中调用 `stop_timer` 函数来停止计时器。同时,在 `closeWindow` 函数中也调用了 `stop_timer` 函数来确保在关闭窗口之前停止计时器。
阅读全文