首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用tkinter中的按钮停止阅读使用fluidsynth创建的笔记

使用tkinter中的按钮停止阅读使用fluidsynth创建的笔记
EN

Stack Overflow用户
提问于 2019-01-03 05:06:25
回答 1查看 67关注 0票数 0

我在python2-7上,我想在tkinter中有一个按钮,它可以停止阅读用fluidsynth创建的笔记。

我发现常见的解决方案是像这样使用time.after:How do you create a Tkinter GUI stop button to break an infinite loop?

但在我的例子中,我不能使用它,因为我需要在noteon和noteoff之间有一段时间来给出我的笔记的持续时间。此外,我只想在单击start时播放音符(而不是像链接中的解决方案那样在开始时播放)。

所以我创建了这个代码,但是它不能工作,因为var_start总是被初始化为int:

代码语言:javascript
复制
from tkinter import*
import fluidsynth
import time

fs=fluidsynth.Synth()
fs.start(driver='alsa', midi_driver='alsa_seq')
org_charge = fs.sfload("organ.sf2")
fs.program_select(0,org_charge, 0, 0)
time.sleep(1)

var_start=int

def start():
    global var_start
    var_start=1

def stop():
    global var_start
    var_start=0

root=Tk()

if var_start==1:
    fs.noteon(0,67,127)
    time.sleep(1)
    fs.noteoff(0,67)
    fs.noteon(0,71,127)
    time.sleep(1)
    fs.noteoff(0,71)
    fs.noteon(0,74,127)
    time.sleep(1)
    fs.noteoff(0,74)

Button(root, text='start', command= start).pack(padx=10, pady=10)    
Button(root, text='stop', command= stop).pack(padx=10, pady=10)    

root.mainloop()

我没有其他想法来重塑我的代码...有人能帮帮我吗?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-03 15:22:22

您在语句var_start=int中将var_start初始化为int,因此将永远不会执行if var_start==1:中的代码块。并且您的start()函数只是将var_start更改为1,并且永远不会开始播放音符,因此不会发生任何事情。

千万不要在主线程中调用time.sleep(),因为它会阻塞tkinter主循环。您可以使用.after(...)来模拟播放循环,下面是一个示例代码块:

代码语言:javascript
复制
playing = False

def play_notes(notes, index, noteoff):
    global playing
    if noteoff:
        fs.noteoff(0, notes[index])
        index += 1      # next note
    if playing and index < len(notes):
        fs.noteon(0, notes[index], 127)
        # call noteoff one second later
        root.after(1000, play_notes, notes, index, True)
    else:
        # either stopped or no more note to play
        playing = False
        print('done playing')

def start_playing():
    global playing
    if not playing:
        print('start playing')
        playing = True
        notes = [67, 71, 74, 88, 80, 91]
        play_notes(notes, 0, False)
    else:
        print('already playing')

def stop_playing():
    global playing
    if playing:
        playing = False
        print('stop playing')
    else:
        print('nothing playing')

Button(root, text='Start', command=start_playing).pack(padx=10, pady=10)
Button(root, text='Stop', command=stop_playing).pack(padx=10, pady=10)

这只是一个示例,您可以根据需要对其进行修改。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54013183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档