完整代码链接:https://download.youkuaiyun.com/download/qq_34162147/54904655
本章节是续篇。如未了解相关内容,请查阅以下链接。
串网直通车——界面篇(Python+Tkinter)_不尽之野火-优快云博客
串网直通车——串口篇(Python+serial+threading)_不尽之野火-优快云博客
串网直通车——网口篇(Python+socket+threading)_不尽之野火-优快云博客
本章节主要讲述的是一些优化的操作。
1、同时开关
在init_window.mainloop()语句之前添加以下代码,可以实现点击“不尽之野火”,同时开关串口和网口的功能。以下代码在main之内。
def two_ctrl():
global main_state
global com_state
global net_state
if(main_state==0):
main_state=1
if(com_state==0):
com_ctrl(
cn_var=com_var,cp_var=init_com_num.get(),cr_var=init_com_rate.get(),
cl_var=com_led,p0=com_light0,p1=com_light1)
else:
pass
if(net_state==0):
net_ctrl(nn_var=net_var,lip_var=local_IP_text.get(),lp_var=local_port_text.get(),
oip_var=opposite_IP_text.get(),op_var=opposite_port_text.get(),
nl_var=net_led,p0=net_light0,p1=net_light1)
else:
pass
else:
main_state=0
if(com_state==1):
com_ctrl(
cn_var=com_var,cp_var=init_com_num.get(),cr_var=init_com_rate.get(),
cl_var=com_led,p0=com_light0,p1=com_light1)
else:
pass
if(net_state==1):
net_ctrl(nn_var=net_var,lip_var=local_IP_text.get(),lp_var=local_port_text.get(),
oip_var=opposite_IP_text.get(),op_var=opposite_port_text.get(),
nl_var=net_led,p0=net_light0,p1=net_light1)
else:
pass
2、关闭窗口
为了点击窗口右上角的X按钮的时候正常关闭程序,需要进行优化。增加了关闭函数。在外层增加如下代码。
def close_all():
# global ser #引用但不改变参数,无需global
# global udp_socket #引用但不改变参数,无需global
global com_state
global net_state
com_state=0
net_state=0
try:
if ser.is_open :
ser.close() # 关闭串口
else:
pass
except Exception:
pass
try:
udp_socket.close()# 关闭网口
except Exception:
pass
其次,在init_window.mainloop()语句之前添加以下代码,将窗口关闭按钮进行绑定。此部分代码在main之内。
def on_closing():
close_all()
init_window.destroy()
init_window.protocol("WM_DELETE_WINDOW", on_closing)
3、打包发布
在Python根目录通过命令pip.exe install pyinstaller进行安装模块。
我的代码和图标存放路径是“E:\我才必用\串网直通车”。如图所示,在代码路径文件夹顶部地址栏输cmd,进入控制台,输入类似以下内容,回车即可打包。其中,-F是指定打包后只生成一个exe格式的文件,-i 是给应用程序添加图标,–noconsole 使用窗口,无控制台。在dist文件夹会生成一个exe文件。双击即可运行。
pyinstaller -F -i E:\我才必用\串网直通车\tube.ico 串网直通车.py --noconsole