Python做串口面板

Python面板实现modbusRTU通讯

  • 概述
  • 面板代码
  • 运行画面

概述

Python目前开放的Tkinter做人机界面软件非常合适。这次用python来制作一个显示面板。不说废话了,上代码。

面板代码

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

from ctypes import *

from datetime import datetime
import time
import threading

bComOpen = False
SerialPort = None
wp4084_01_x = 0
stop_threads = False

# 屏幕上显示当前时间,并不断更新
def count(para='hi', sleep=1.0):
    global stop_threads
    while True:
        if stop_threads:
            break
        g_lTime.set(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        #print(para)
        time.sleep(sleep)
def serialTick(para='hi', sleep=1.0):
    global SerialPort
    global bComOpen
    global stop_threads
    print(bComOpen)
    while True:
        if stop_threads:
            break
        if bComOpen:
            SerialPort.write(bytes.fromhex('010300000002C40B'))
            try:
                xData = SerialPort.read_all()
            except:
                print('read not succuse')
            if ( len(xData) == 9):
                wp4084_01_x = (xData[5] << 24) + (xData[6] << 16) + (xData[3] << 8) + xData[4]
                print(xData)
                v = c_int32(wp4084_01_x)
                print(v.value)
                e1_1Text.set(v.value)
            #print('Test')
        time.sleep(sleep)

th1 = threading.Thread(target=serialTick)
th = threading.Thread(target=count)

root = Tk()             # 初始化Tk
root.title('欢迎百分表调试面板 - Commission Pad V2.01')
root.geometry('800x500')
root.resizable(width=False, height=True)

def b1_click():
    print('The buttun pressed')
    port = cbox2.get()
    baud = int(cbox1.get())
    try:
        global SerialPort
        SerialPort = serial.Serial(port, baud)
        global bComOpen
        bComOpen = True
        c2.config(background='lime')
        print('th1.is_alive = %d' %th1.is_alive())
        #if (not th1.is_alive()):
            #th1.start()
        #else:
            #th1.run()
    except Exception as e:
        print('Exception:{}'.format(e))
        print(SerialPort)

def b2_click():
    print('Buttun 1 clicked!')
    global root
    root.destory()

def b3_click():
    #print(SerialPort.isOpen
    if SerialPort is not None and SerialPort.isOpen:
        SerialPort.close()
        global bComOpen
        bComOpen = False
        c2.config(background='red')
    print(SerialPort)
g_lTime = StringVar()
g_lTime.set(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
g_butText = StringVar()
g_but1Text = StringVar()

btn1 =Button(frame_title, text='退出面板', font=('微软雅黑',12), command=root.destroy)
#button=Button(frame_title,text='退出',font=('微软雅黑',12), justify='right', command=root.destroy)
btn2 = Button(frame_title,text='关闭串口',font=('微软雅黑',12), justify='right', command=b3_click)

cbox1 = ttk.Combobox(frame_title, width = 16, state = 'readonly')
cbox2 = ttk.Combobox(frame_title, width = 16, state = 'readonly')

lTStr = Label(frame_title, textvariable=g_lTime, bg='blue',fg='white',
              font=('Arial 12 bold'),width=20,height=1)

Port = StringVar()      #端口号字符串
Port_List = ttk.Combobox(frame_title, width=12, textvariable=Port, state='readonly')
ListPorts = list(serial.tools.list_ports.comports())
Port_List['values'] = [i[0] for i in ListPorts]
#Port_list.current()# 初始显示表中第一个值
if len(ListPorts) <= 0:
    cbox2['values'] = ['No Com Port']
else:
    cbox2['values'] = [i[0] for i in ListPorts]
cbox1['values'] = ['选择波特率', '9600', '19200', '38400', '115200']

lTStr.grid(row=0, column=0)
btn1.grid(row=0, column=1)
#button.grid(row=0, column=2)
btn2.grid(row=2, column=3)
cbox2.grid(row=2, column=1)
cbox1.grid(row=3, column=1)
g_butText.set('打开串口')
Label(frame_title, text='串口连接状态:',font=('Arial 12 bold'),
      bg = 'blue', fg = 'white').grid(row=1, column=0)
Label(frame_title, text='选择串口:',font=('Arial 12 bold'),
      bg = 'blue', fg = 'white').grid(row=2, column=0)
Label(frame_title, text='选择波特率:',font=('Arial 12 bold'),
      bg = 'blue', fg = 'white').grid(row=3, column=0)

c2 = Canvas(frame_title, width=80, height=30,  bg='red')
button=Button(frame_title,textvariable=g_butText,font=('微软雅黑',12),command=b1_click)

c2.grid(row=1, column=1)
#Port_list.grid(row=0, column=2)  # 设置其在界面中出现的位置
button.grid(row=1, column=3)

Label(frame_status, text='百分表读数1:',
      font=('Arial 12 bold')).grid(row=0, column=0)
Label(frame_status, text='百分表读数',font=('Arial 12 bold'),
      bg = 'blue', fg = 'white').grid(row=1, column=0)
e1_1Text = StringVar()
e1_1 = Entry(frame_status, textvariable = e1_1Text,
             font=('微软雅黑',12, 'bold'), justify = 'center')
e1_1.grid(row=1, column=1)
e1_1Text.set('0.01')

th.daemon=True
th.start()
th1.daemon=True
th1.start()

运行画面

Python做串口面板_第1张图片

你可能感兴趣的:(python,开发语言)