前一篇介绍在pycharm中如何配置pyqt5,并创建一个Mainwindow,成功显示出这个主窗口。本篇介绍通过上位机界面,读取和写入PLC内的数据,并显示出来。
1、新建一个Mainwindow主窗口。把每个控件的objectName的默认名称修改成自己想要的名字。界面布局如下:
2、将.ui转换成.py文件。程序太长,就不粘贴进来了。
3、新建一个python file,来调用生成的python文件。新建一个类继承QMainWindow和Ui_MainWindow。这样就可以运行一个MainWindow窗口。
from PyQt5.QtWidgets import QMainWindow, QApplication
from xiaobai_UI import Ui_MainWindow
import sys
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.widget_init()
if __name__ == '__main__':
app = QApplication(sys.argv)
MainWindow = MainWindow()
MainWindow.show()
sys.exit(app.exec_())
4、初始化一下控件。
def widget_init(self):
self.ip.setText("192.168.1.20")
self.rack.setText("0")
self.slot.setText("1")
self.datatype.addItems(['Bool', 'Int', 'Real', 'String'])
5、添加连接和断开连接按钮功能。Client()类里有一个get_connected()方法,当连接PLC成功,返回True,将label_9的文本改为已连接。self.ip.text()获取控件ip的文本。rack和slot一样,只不过他们的类型是int。
def connect_clicked(self):
try:
ip = self.ip.text()
rack = int(self.rack.text())
slot = int(self.rack.text())
self.client.connect(ip, rack, slot)
if self.client.get_connected():
self.label_9.setText("已连接")
except Exception as e:
print(e)
def disconnect_clicked(self):
if self.client.get_connected():
self.client.disconnect()
self.label_9.setText("")
6、给按钮绑定事件。注意:self.connect_clicked和self.disconnect_clicked不要括号
self.connectButton.clicked.connect(self.connect_clicked)
self.disconnectBUtton.clicked.connect(self.disconnect_clicked)
7、添加读取和写入按钮功能。
def write_clicked(self):
db_number = int(self.dbnumber.text())
offset = int(self.offset.text())
data = int(self.data.text())
byte_array = struct.pack('!i', data)
self.client.write_area(0x84, db_number, offset, byte_array)
def read_clicked(self):
db_number = int(self.dbnumber.text())
byte = int(self.offset.text().split('.')[0])
bit = int(self.offset.text().split('.')[1])
data_type = self.datatype.currentText()
try:
if data_type == 'Bool':
read_data = self.client.read_area(0x84, db_number, 0, byte+2)
data = snap7.util.get_bool(read_data, byte, bit)
self.readdata.setText(str(data))
if data_type == 'Int':
read_data = self.client.read_area(0x84, db_number, 0, byte+2)
data = snap7.util.get_int(read_data, byte)
self.readdata.setText(str(data))
if data_type == 'Real':
read_data = self.client.read_area(0x84, db_number, 0, byte+4)
data = snap7.util.get_real(read_data, byte)
self.readdata.setText(str(data))
if data_type == 'String':
read_data = self.client.read_area(0x84, db_number, 0, byte+256)
data = snap7.util.get_string(read_data, byte, 32)
self.readdata.setText(str(data))
except Exception as e:
print(e)
8、运行界面试一试。
简单的界面控制PLC内的数据,感谢支持!!!
本文暂时没有评论,来添加一个吧(●'◡'●)