Python如何影响运行程序

时间:2017-12-06 19:19:39

标签: python kivy

按钮开始闹钟开始响铃闹钟。我想通过按钮停止响铃停止闹钟。我不知道是否会影响正在运行的程序。我该如何修复功能 stop_alarm

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget

import winsound

class ControlPanel(BoxLayout):
    def __init__(self, **kwargs):
        # make sure we aren't overriding any important functionality
        super(ControlPanel, self).__init__(**kwargs)
        self.alarm_status = True
        self.orientation = "vertical"

        butOn = Button(text = "Start alarm: ", on_release = self. start_alarm)
        butStop = Button(text = "Stop alarm: ", on_release = self.stop_alarm)

        self.add_widget(butOn)
        self.add_widget(butStop)

    def start_alarm(self, obj):
        while self.alarm_status == True:
            winsound.PlaySound("alarm.wav", winsound.SND_FILENAME)

    def stop_alarm(self, obj):
        self.alarm_status = False

class LifeApp(App):
    def build(self):     
        return ControlPanel()

if __name__ == '__main__':
    LifeApp().run()

1 个答案:

答案 0 :(得分:0)

您的代码的主要问题是您的主GUI线程上有一个while循环。所以你需要做的是在与主GUI线程不同的线程上运行start_alarm,以便GUI线程能够响应。

至于下次无法播放闹钟,你没有再次将alarm_status标志设置为True。一旦你有了,你可以多次开始和停止声音。

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.widget import Widget
import time
import winsound
import threading

class ControlPanel(BoxLayout):
    def __init__(self, **kwargs):
        # make sure we aren't overriding any important functionality
        super(ControlPanel, self).__init__(**kwargs)
        self.alarm_status = True
        self.orientation = "vertical"

        butOn = Button(text = "Start alarm: ", on_release = self.start_thread)
        butStop = Button(text = "Stop alarm: ", on_release = self.stop_alarm)

        self.add_widget(butOn)
        self.add_widget(butStop)

    def start_alarm(self, obj):
        while self.alarm_status == True:
            winsound.PlaySound("alarm.wav", winsound.SND_FILENAME)
        #Set Alarm_Status True so that next time it works
        self.alarm_status = True

    def stop_alarm(self, obj):
        self.alarm_status = False

    #Function to run your start_alarm on a different thread
    def start_thread(self,obj):
        t1 = threading.Thread(target=self.start_alarm,args=(obj,))
        t1.start()

class LifeApp(App):
    def build(self):     
        return ControlPanel()

if __name__ == '__main__':
    LifeApp().run()

希望这有帮助!