Skip to main content
 首页 » 编程设计

python之如何使用 Tkinter 按钮跳出无限循环

2025年01月19日10lyhabc

我正在使用 Tkinter 作为 UI 的程序工作。我正在编写代码来重复播放音频。我正在使用 pygame.mixer.music() 播放音频。

在 UI 中,我创建了两个按钮(“开始”和“停止”)。我将一个包含循环结构的方法附加到开始按钮,这样当按下开始按钮时,循环将被执行并开始重复播放音频。现在我不知道如何附加停止按钮。就像,当按下停止按钮时,控件应该退出循环。我可以使用中断或其他类似的东西吗?我对中断的概念完全陌生。要继续进行,请帮助我处理什么样的中断,它的库是什么等等。如果没有,请帮助我如何继续使用停止按钮。

这是我的代码:

from pygame import * 
from Tkinter import * 
import time 
root = Tk() 
root.geometry("1000x200") 
root.title("sampler") 
m=1 
n=1 
mixer.init() 
def play(): 
 
    while m==1: 
 
        print 'playing' 
        mixer.music.load('audio 1.mp3') 
        mixer.music.play() 
        time.sleep(n) 
 
start = Button(root, text="play", command = play) 
start.pack() 
stop = Button(root, text="Stop") 
stop.pack() 
mainloop() 

n 定义每次循环播放音频的时长。

请您参考如下方法:

Python 并不完全支持中断,最接近的可能是某种信号处理程序,通过它的 signal 支持。图书馆。然而,它们可能不适用于 Tkinter(或 pygame),所以我认为这不是一个好方法——而且它们也不是必需的,因为你可以处理你想做的事情在 Tkinter 的 mainloop() 中。

虽然它可能看起来有些复杂,但我建议的实现方式是将大部分播放控制功能封装在一个 Python class 中。这将减少全局变量的使用,这将使程序更易于调试和进一步开发(因为面向对象编程的许多优点 — 也称为 OOP)。

下面说明了我的意思。请注意,我使用的是 Python 3,因此必须对您的代码进行一些额外的更改才能使其适用于该版本。我不确定,但这个版本应该也能在 Python 2 中工作,除非你需要按照指示更改 Tkinter 模块的 import。

from pygame import * 
from tkinter import *  # Change to "from Tkinter import *" for Python 2.x. 
 
class PlayController(object): 
    def __init__(self, mixer, music_filename, polling_delay): 
        self.mixer = mixer 
        self.music_filename = music_filename 
        self.polling_delay = polling_delay  # In milliseconds. 
        self.playing = False 
 
    def play(self): 
        if self.playing: 
            self.stop() 
        self.mixer.music.load(self.music_filename) 
        self.mixer.music.play(-1)  # -1 means to loop indefinitely. 
        self.playing = True 
        root.after(self.polling_delay, self.check_status)  # Start playing check. 
 
    def stop(self): 
        if self.playing: 
            self.mixer.music.stop() 
            self.playing = False 
 
    def check_status(self): 
        if self.playing: 
            print('playing') 
        root.after(self.polling_delay, self.check_status)  # Repeat after delay. 
 
root = Tk() 
root.geometry("1000x200") 
root.title("Sampler") 
mixer.init() 
 
play_control = PlayController(mixer, 'tone.wav', 1000) 
Button(root, text="Play", command=play_control.play).pack() 
Button(root, text="Stop", command=play_control.stop).pack() 
 
mainloop()