2017-10-17 156 views
0

我有一个菜单级联,它具有用于将背景音乐切换到应用程序(使用python tkinter)的开/关按钮。基于CheckButton切换音乐开关

当应用程序运行时(通过root.mainloop()),背景音乐已经播放,并且checkbutton旁边有一个刻度,就像我想要的那样(指示其开启)。

当我关闭checkbutton时,声音由于self.sound_off命令而关闭。

问题是当我再次单击按钮(并出现勾号)时,声音无法打开。我意识到这是因为我在checkbutton中指定的命令是command = sound.off()。但我不知道如何制作,以便当出现勾号时声音播放(或取消暂停),当勾号不在时声音暂停。

# within def __init__(self, master) of the app 
self.add_sound() 

self._value = IntVar(value=1) 

menubar = tk.Menu(master) 
master.config(menu=menubar) 
filemenu = tk.Menu(menubar)   
filemenu.add_checkbutton(label="Music", onvalue=1, offvalue=0, variable= 
          self._value, command=self.sound_off) 


def add_soud(self): 
    pygame.mixer.music.load("Sound.mp3") 
    pygame.mixer.music.set_volume(0.2) 
    pygame.mixer.music.play(-1) 

def sound_off(self): 
    pygame.mixer.music.pause() 

def sound_on(self): 
    pygame.mixer.music.unpause() 

#Am I supposed to have some sort of 'if' statement to check if the onvalue is 
#0 or 1? 

任何帮助表示赞赏。

回答

0

这会工作

filemenu.add_checkbutton(label="Music", onvalue=1, offvalue=0, variable= 
         self.sound_value, command=self.sound_manipulation) 

def sound_manipulation(self): 
    if self.sound_value.get() == 1: 
     pygame.mixer.music.unpause() 
    else: 
     pygame.mixer.music.pause()