【问题标题】:Start python tkinter stopwatch based on arduino serial output基于arduino串口输出启动python tkinter秒表
【发布时间】:2017-09-15 18:35:12
【问题描述】:

我有一个连接到按钮的 arduino。按下按钮时,通过串行发送串行输出 1。我希望在按下按钮时启动 python tkinter 秒表。目前我知道 1 正在被 python 串行读取读取。并在 python 终端打印出来。但我无法控制 tkinter 秒表。 PS:我对python相当陌生。以下是我当前的代码。

from tkinter import *
import time
import serial

ser = serial.Serial(
    port='COM4',\
    baudrate=57600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=10)

print("connected to: " + ser.portstr)



class StopWatch(Frame):  
    """ Implements a stop watch frame widget. """                                                                
    def __init__(self, parent=None, **kw):        
        Frame.__init__(self, parent, kw)
        self._start = 0.0        
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()               
        self.makeWidgets()      

    def makeWidgets(self):                         
        """ Make the time label. """
        l = Label(self, textvariable=self.timestr)
        self._setTime(self._elapsedtime)
        l.pack(fill=X, expand=NO, pady=2, padx=2)                      

    def _update(self): 
        """ Update the label with elapsed time. """
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._timer = self.after(50, self._update)

    def _setTime(self, elap):
        """ Set the time string to Minutes:Seconds:Hundreths """
        minutes = int(elap/60)
        seconds = int(elap - minutes*60.0)
        hseconds = int((elap - minutes*60.0 - seconds)*100)                
        self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))

    def Start(self):                                                     
        """ Start the stopwatch, ignore if running. """
        if not self._running:            
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1        

    def Stop(self):                                    
        """ Stop the stopwatch, ignore if stopped. """
        if self._running:
            self.after_cancel(self._timer)            
            self._elapsedtime = time.time() - self._start    
            self._setTime(self._elapsedtime)
            self._running = 0

    def Reset(self):                                  
        """ Reset the stopwatch. """
        self._start = time.time()         
        self._elapsedtime = 0.0    
        self._setTime(self._elapsedtime)


def main():
    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)


    root.mainloop()

if __name__ == '__main__':
    main()

    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)
    count=1

    while True:
        for line in ser.read():

            print(chr(line))
            count = count+1
            if chr(line) == '1':
                sw.Start()

    ser.close()

编辑:根据我的评论回答,我已经开始工作了。下面是工作代码。

from tkinter import *
import time
import serial

class StopWatch(Frame):  
    """ Implements a stop watch frame widget. """                                                                
    def __init__(self, parent=None, **kw):        
        Frame.__init__(self, parent, kw)
        self._start = 0.0        
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()               
        self.makeWidgets()      

    def makeWidgets(self):                         
        """ Make the time label. """
        l = Label(self, textvariable=self.timestr)
        self._setTime(self._elapsedtime)
        l.pack(fill=X, expand=NO, pady=2, padx=2)                      

    def _update(self): 
        """ Update the label with elapsed time. """
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._timer = self.after(50, self._update)

    def _setTime(self, elap):
        """ Set the time string to Minutes:Seconds:Hundreths """
        minutes = int(elap/60)
        seconds = int(elap - minutes*60.0)
        hseconds = int((elap - minutes*60.0 - seconds)*100)                
        self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))

    def Start(self):                                                     
        """ Start the stopwatch, ignore if running. """
        if not self._running:            
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1        

    def Stop(self):                                    
        """ Stop the stopwatch, ignore if stopped. """
        if self._running:
            self.after_cancel(self._timer)            
            self._elapsedtime = time.time() - self._start    
            self._setTime(self._elapsedtime)
            self._running = 0

    def Reset(self):                                  
        """ Reset the stopwatch. """
        self._start = time.time()         
        self._elapsedtime = 0.0    
        self._setTime(self._elapsedtime)

def Read():
        ser = serial.Serial(
        port='COM4',\
        baudrate=57600,\
        parity=serial.PARITY_NONE,\
        stopbits=serial.STOPBITS_ONE,\
        bytesize=serial.EIGHTBITS,\
            timeout=10)

        print("connected to: " + ser.portstr)
        count=1

        while True:
                for line in ser.read():

                    print(chr(line))
                    count = count+1
                    return chr(line)

        ser.close()

def main():
    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)
    ser = Read()

    if ser == '1':
        sw.Start()

    root.mainloop()

if __name__ == '__main__':
    main()

【问题讨论】:

  • 一个明显的问题是sw.Start 没有调用该函数。它必须是sw.Start()
  • @BryanOakley 我已经更新了我的代码,因为 gui 无法启动。现在 gui 启动但秒表不会启动。当我关闭 gui 时,命令行界面显示 sw 未定义。
  • 那么你的缩进在你的if __name__ == '__main__':声明中是关闭的
  • @SierraMountainTech 怎么样?另外,如果我将 root = Tk() sw = StopWatch(root) sw.pack(side=TOP) 放在 while true 语句之上,什么也不会发生
  • count=1 while True: 声明和 ser.close() 都应该与 main() 一致,而且除非你的意图,否则它甚至都不会运行,直到你的应用程序关闭。

标签: python tkinter arduino pyserial


【解决方案1】:

你的main()if __name__ 语句有点破。

根据我在您的代码中看到的内容,您的代码不会像您认为的那样运行。

您应该只创建一个Tk() 的实例,并且在您的代码中它被编写了两次。

请注意,您在root.mainloop() 之后编写的任何代码在mainloop() 结束之前都不会运行。届时,您的程序将关闭,并且由于您的 main() 语句的其余部分,将创建一个新实例。

这可能不是你的意图。

这个:

def main():
    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)


    root.mainloop()

if __name__ == '__main__':
    main()

    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)
    count=1

    while True:
        for line in ser.read():

            print(chr(line))
            count = count+1
            if chr(line) == '1':
                sw.Start()

    ser.close()

应该是这样的:

def main():
    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)

    count=1
    while True:
        for line in ser.read():
            print(chr(line))
            count = count+1
            if chr(line) == '1':
                sw.Start()

    ser.close()

    root.mainloop()

if __name__ == '__main__':
    main()

这不是试图回答您的整体问题,因为我还没有详细查看您的所有代码,但是很难将其放在评论中,所以我在这里写了它。

更新:

我无法在任何与串行相关的内容上测试您的代码,但是我确实修改了您的 for 循环以测试您的代码的功能。话虽如此,我相信您想在 while 循环之前将 ser = serial.Serial() 的内容移动到 main() 函数中。另外,也许您应该稍微更改一下 while 循环语句。目前,while True: 语句将永远运行。

改为使用类似的东西。

x = True
while x == True:
    # do stuff
    x = False
    sw.Start()

最后我认为你的代码应该是这样的:

from tkinter import *
import time
import serial


class StopWatch(Frame):  
    """ Implements a stop watch frame widget. """                                                                
    def __init__(self, parent=None, **kw):        
        Frame.__init__(self, parent, kw)
        self._start = 0.0        
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()               
        self.makeWidgets()      

    def makeWidgets(self):                         
        """ Make the time label. """
        l = Label(self, textvariable=self.timestr)
        self._setTime(self._elapsedtime)
        l.pack(fill=X, expand=NO, pady=2, padx=2)                      

    def _update(self): 
        """ Update the label with elapsed time. """
        self._elapsedtime = time.time() - self._start
        self._setTime(self._elapsedtime)
        self._timer = self.after(50, self._update)

    def _setTime(self, elap):
        """ Set the time string to Minutes:Seconds:Hundreths """
        minutes = int(elap/60)
        seconds = int(elap - minutes*60.0)
        hseconds = int((elap - minutes*60.0 - seconds)*100)                
        self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))

    def Start(self):                                                     
        """ Start the stopwatch, ignore if running. """
        if not self._running:            
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1        

    def Stop(self):                                    
        """ Stop the stopwatch, ignore if stopped. """
        if self._running:
            self.after_cancel(self._timer)            
            self._elapsedtime = time.time() - self._start    
            self._setTime(self._elapsedtime)
            self._running = 0

    def Reset(self):                                  
        """ Reset the stopwatch. """
        self._start = time.time()         
        self._elapsedtime = 0.0    
        self._setTime(self._elapsedtime)


def main():
    root = Tk()
    sw = StopWatch(root)
    sw.pack(side=TOP)
    ser = serial.Serial(
                        port='COM4',\
                        baudrate=57600,\
                        parity=serial.PARITY_NONE,\
                        stopbits=serial.STOPBITS_ONE,\
                        bytesize=serial.EIGHTBITS,\
                            timeout=10)
    x = True
    count=1
    while x == True:
        for line in ser.read():
            print(chr(line))
            count = count+1
            if chr(line) == '1':
                sw.Start()

    root.mainloop()

if __name__ == '__main__':
    main()

【讨论】:

  • 这会将串行输出打印到 python 命令行。但现在秒表 gui 甚至无法启动。
  • 如果我删除代码的ser = serial.Serial() 部分,秒表窗口会打开。
  • @是的。但现在 ser 没有定义。并且串行的串行输出不读取
  • @MohamedAthif 正确,但是这告诉您ser = serial.Serial() 中的代码或其位置有问题。
  • 我可以把它放在哪里?我需要那段代码来读取序列号。它现在正确打印出串行输出
猜你喜欢
  • 2014-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-29
相关资源
最近更新 更多