在Python中使用Button(GUI)和WhileLoop

时间:2017-12-07 09:46:46

标签: python raspberry-pi

我在Raspberry PI上从命令行开始使用简单的Python代码,如:

import ...

def def_1(....)
def def_2(....)

 if __name__ == ‘__main__’:
    while:
         def_1(....)
         def_2(....)

所以,我想添加3个按钮(GUI):

  1. 仅启动def_1(无限循环)
  2. 仅启动def_2(无限循环)
  3. Whitch end def_1或def_2
  4. 我怎么做?

2 个答案:

答案 0 :(得分:0)

首先选择要使用pyqt,tkinter ...

的框架

然后参考api的doc,其中特别记录了如何使用按钮来构造按钮。

import Tkinter
import tkMessageBox

top = Tkinter.Tk()

def helloCallBack():
    tkMessageBox.showinfo( "Hello Python", "Hello World")

B = Tkinter.Button(top, text ="Hello", command = helloCallBack)

B.pack()
top.mainloop()

在这个迷你示例中,您可以看到,如何在按钮初始化中调用函数。使用命令定义。有关gui编程的更多详细信息,请编辑一些教程

来自https://www.tutorialspoint.com/python/tk_button.htm

的示例

答案 1 :(得分:0)

在Raspberry PI上我使用Kivy进行GUI。 你可以这样做:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

import threading
import time

class ButtonDemo(BoxLayout):
    def __init__(self, **kwargs):
        super(ButtonDemo, self).__init__(**kwargs)
        self.orientation = "vertical"
        self.add_widget(Button(text = "Action #1", on_press = self.def_1))
        self.add_widget(Button(text = "Action #2", on_press = self.def_2))
        self.add_widget(Button(text = "Stop", on_press = self.stop))

        loop_thread_1 = threading.Thread()
        loop_thread_2 = threading.Thread()
        loop_running_1 = False
        loop_running_2 = False

    def def_1(self, instance):
        print("DEF 1")
        self.loop_thread_1 = threading.Thread(target = self.loop_1)
        self.loop_thread_1.start()

    def def_2(self, instance):
        self.loop_thread_2 = threading.Thread(target = self.loop_2)
        self.loop_thread_2.start()

    def stop(self, instance):
        if self.loop_running_1:
            self.loop_running_1 = False

        if self.loop_running_2:
            self.loop_running_2 = False

    def loop_1(self):
        self.loop_running_1 = True
        while self.loop_running_1:
            print("loop 1")
            time.sleep(1)

    def loop_2(self):
        self.loop_running_2 = True
        while self.loop_running_2:
            print("loop 2")
            time.sleep(1)

class TestButtonApp(App):
    def build(self):
        return ButtonDemo()

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

每个循环都以新线程开始,因此程序不会冻结。停止按钮可以根据需要停止运行线程。