Python tkinter делает серийную работу с кнопками - PullRequest
0 голосов
/ 20 октября 2018

Я новичок в ООП и пытаюсь сделать графический интерфейс для себя.Я хочу сделать симулятор программы.Я читаю серийные данные с Arduino.

Мои вопросы:

  1. Почему кнопка исчезает, когда я получаю серийные данные?Когда отображаются последовательные данные, половина кнопки запуска исчезает.
  2. Как сделать так, чтобы кнопки «Пуск» и «Стоп» работали в коде?Приложение () будет работать всегда, и когда я нажму кнопку запуска, будет запущена функция Application.run (), пока я не нажму кнопку остановки.

Пример кода:

from tkinter import *
import serial
import serial.tools.list_ports as ports

switch=False
class Application(Frame):


    def __init__(self,master,*args,**kwargs):
        Frame.__init__(self,*args,**kwargs)
        ratios=self.GetScreenRatio()
        self.CreateCanvas()
        self.PackWidgets()

    def updateGui(self): 
        self.update()

    def CreateCanvas(self):

        self.canvas=Canvas(root,width=self.winfo_screenwidth(),height=self.winfo_screenheight())
        self.canvas.pack()

    def GetScreenRatio(self):

        self.screen_width = self.winfo_screenwidth()/1920
        self.screen_height = self.winfo_screenheight()/1080

    def PackWidgets(self):

        x_ratio=self.screen_width
        y_ratio=self.screen_height
        letter_ratio=(x_ratio+y_ratio)/2


        self.start_button=Button(root,text='Start',command=self.Start,activeforeground='white',
               bg='green',activebackground='green',fg='white',width=21,height=2,font='bold')
        self.start_button.place(x=120*x_ratio,y=800*y_ratio)

        self.stop_button=Button(root,text='Stop',command=self.Stop,activeforeground='white',
               bg='red',activebackground='red',fg='white',width=21,height=2,font='bold')
        self.stop_button.place(x=760*x_ratio,y=800*y_ratio)

        self.quit_button=Button(root,text='Quit',bg='black',activebackground='black',command=root.destroy,
                                fg='white',activeforeground='white',width=21,height=2,font='bold')
        self.quit_button.place(x=1400*x_ratio,y=800*y_ratio)


        self.bridge_pointer=Label(root,text='Híd neve:',font=("Courier",round(50*letter_ratio)),fg='#0078ef')
        self.bridge_pointer.place(x=1*x_ratio,y=1*y_ratio)
        self.bridge_name=Label(root,font=("Courier",round(50*letter_ratio)),fg='#0078ef')
        self.bridge_name.place(x=400*x_ratio,y=1*y_ratio)
        self.bridge_value=Label(root,text='0.0',font=("Courier",round(200*letter_ratio)),fg='#0078ef')
        self.bridge_value.place(x=200*x_ratio,y=200*y_ratio)
        self.value_prefix=Label(root,text='Kg',fg='#0078ef',font=("Courier", round(100*letter_ratio)))
        self.value_prefix.place(x=390*x_ratio,y=480*y_ratio)

        teglalap=self.canvas.create_rectangle(1*x_ratio,1*y_ratio,50*x_ratio,
                50*y_ratio,fill="#0078ef",width=2)

        teglalap2=self.canvas.create_rectangle(987*x_ratio,612*y_ratio,1165*x_ratio,
                                  602*y_ratio,fill="#909090",width=2)

        teglalap3=self.canvas.create_rectangle(1215*x_ratio,612*y_ratio,1360*x_ratio,
                                  602*y_ratio,fill="#909090",width=2)
    def Start(self):
        self.run()


    def Stop(self):
        #Stop serial connection(stop the Application.run() func)
        pass
    def run(self):
        self.MakeSerial()
        self.Update()
        root.mainloop()

    def MakeSerial(self):
        try:
            for ee in list(ports.comports()):
                if ee.serial_number=='55639313633351A07142':
                    usb=ee.device
            self.ser=serial.Serial(usb,baudrate=57600,timeout=2)
        except UnboundLocalError:
            root.destroy()
            print('Nincs csatlakoztatva az Arduino! ')


    def Update(self):
        try:
            if self.ser.isOpen():
                data = self.ser.readline(self.ser.inWaiting())
                self.bridge_value['text']=data
                self.after(10,self.Update)
                print(data)
            else:
                print('Portot nem lehet megnyitni!')
        except serial.serialutil.SerialException:
            print("Soros kapcsolat megszakadt")
        except AttributeError:
            pass


root=Tk()
root.state('zoomed')
window=Application(root)

Любое хорошее предложение?

Это ошибка:

for c in list(self.children.values()): c.destroy() 
File "C:XXXXX\GUI proba.py", line 77, in destroy 
self.Stop() RecursionError: maximum recursion depth exceeded

1 Ответ

0 голосов
/ 21 октября 2018

Комментарий : когда я нажимаю кнопку выхода, мое окно зависает и ничего не может сделать

Я перегрузил Application.destroy(), который вызывается изroot.destroy().Там мы называем root.destroy(), что приводит к бесконечному циклу.
Изменить def destroy(... на def quit(...


Вопрос : как я могу остановить функцию run () с помощью кнопки останова

Использовать переменную-флаг, например, self.stopUpdate следующим образом:

def __init__(self,master,*args,**kwargs):
   ...
    self.stopUpdate = None
    self.MakeSerial()

def PackWidgets(self):
    ...
    self.quit_button=Button(..., command=self.quit, ...

def quit(self):
    self.Stop()
    # Wait until Update returns
    while self.stopUpdate:
        time.sleep(1)
    root.destroy()

def Start(self):
    self.stopUpdate = False
    self.Update()

def Stop(self):
    self.stopUpdate = True

def Update(self):
    if self.stopUpdate:
        # Indicates Update returns, for self.destroy(...
        self.stopUpdate = False
        return
    try:
        ...

Удалить все вместе

#def run(self):
#    self.MakeSerial()
#    self.Update()
#    root.mainloop()
  • перемещено self.MakeSerial() в __init__(...
  • перемещено self.Update() в self.Start(...
  • перемещаться root.mainloop() внизсценарий.

Примечание :
Плохо отлавливать несколько исключений с помощью одного try: ... except: блока.
Использовать один для .ser.readline(... и один для =data

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...