Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于arduino串行输出启动python tkinter秒表_Python_Tkinter_Arduino_Pyserial - Fatal编程技术网

基于arduino串行输出启动python tkinter秒表

基于arduino串行输出启动python tkinter秒表,python,tkinter,arduino,pyserial,Python,Tkinter,Arduino,Pyserial,我有一个arduino连接到一个按钮。按下按钮时,通过串行发送串行输出1。我想让python tkinter秒表在按下按钮时启动。目前我知道python串行读取正在读取1。并在python终端上打印。但是我不能控制tkinter秒表。PS:我对python相当陌生。下面是我当前的代码 from tkinter import * import time import serial ser = serial.Serial( port='COM4',\ baudrate=57600,

我有一个arduino连接到一个按钮。按下按钮时,通过串行发送串行输出1。我想让python tkinter秒表在按下按钮时启动。目前我知道python串行读取正在读取1。并在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()
您的
main()
if\uu\u name\uu
语句有点不正确

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

您应该只创建一个
Tk()
的实例,并且在您的代码中会写入两次

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

这可能不是你的意图

这:

应该是这样的:

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()
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()
这并不是试图回答您的总体问题,因为我还没有详细查看您的所有代码,但很难在注释中添加它,所以我在这里写了它

更新:

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

相反,使用这样的东西

x = True
while x == True:
    # do stuff
    x = False
    sw.Start()
最后,我认为您的代码应该如下所示:

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()
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()

一个明显的问题是
sw.Start
不调用该函数。它必须是
sw.Start()
@BryanOakley我已经更新了我的代码,因为gui无法启动。现在gui启动,但秒表不会启动。当我关闭gui时,命令行界面显示sw未定义。如果if\uuuuuu name\uuuuu=='\uuuu main\uuuu':statement@SierraMountainTech怎么样?另外,如果我将root=Tk()sw=StopWatch(root)sw.pack(side=TOP)放在while true语句上方,则
count=1
while true:语句和
ser.close()
应该与
main()一致
此外,除非您有意关闭应用程序,否则在应用程序关闭之前,它都不会运行。这会将串行输出打印到python命令行。但是现在秒表gui甚至无法启动。如果我删除代码的
ser=serial.serial()
部分,秒表窗口确实会打开。@是的。但现在ser还没有定义。串行输出的串行输出不可用read@MohamedAthif但是,如果正确,则表明某些东西正在使用
ser=serial.serial()
中的代码或其位置写入。我可以将其放置在何处?我需要这段代码来读取序列号。从现在起,它正确地打印出串行输出