在体验uiautomation这个库的时候发现了这个有意思的功能,于是就把相关代码提取出来,可以实现在不安装第三方库的情况下用自带的ctypes库改变python命令窗口的标题。(ctypes在python3.4及以下版本需要pip安装)
这个功能有时候还是有点用的,我经常会同时运行多个python程序,这些程序有自己的gui界面,有的使用了多进程方式来创建gui。经常在手动结束某个程序GUI后发现还有残留的python控制台窗口(就是名称为"C:\windows\py.exe"的这个东西),这样下来,有些使用了socket功能的程序也没有完全关闭,在下一次启动的时候会报socket只能有一个的错误。但我又不能直接关控制台,因为还需要维持其他程序的运行状态。
但当我把每个程序的python命令窗口名称自定义后,我就可以在它的GUI界面中添加一个有终止整个程序(GUI+命令窗口)运行功能的按钮了,可以通过这个按钮只结束这个程序的GUI和命令窗口而不影响其他程序。这个功能是通过pywin32库中的win32gui和win32con来实现的。
贴上代码(我的python3.8 以及 3.10运行没问题):
import ctypes
import win32gui
import win32con
import multiprocessing
from datetime import datetime,timedelta
from tkinter import *
from time import sleep,strftime
# 设置python程序控制台的标题
Custom_titles = '你一定要看看好了吗'
ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(Custom_titles)) # 就这一句代码就够了,剩下的都是配角儿
def exit_process():
global Custom_titles
win32gui.PostMessage(win32gui.FindWindow(0,Custom_titles),win32con.WM_CLOSE,0,0)
def exit_gui():
print('略~略~略~略~略~略~')
exit() # 这里只会结束GUI界面,控制台还在运行
def gui():
root = Tk()
root.title('不要了~')
x = root.winfo_screenwidth() # 获取屏幕的宽度像素
y = root.winfo_screenheight() # 获取屏幕的高度像素
root.geometry('+' + str(x - 400) + '+' + str(y - 300)) # 屏幕右下角向左400像素,向上300像素
Button(root,text = '__体验一下exit函数__',command = exit_gui).grid(row = 0,column = 0)
Label(root,text = '点上面这个,控制台还在跑').grid(row = 1,column = 0)
Button(root,text = '看一下控制台关了没',relief = 'groove',command = exit_process).grid(row = 2,column = 0)
root.mainloop()
if __name__ == '__main__':
# 搞一个主进程,有限时运行的功能,到期自动结束
now_time = datetime.now()
show_now_time = now_time.strftime('%Y-%m-%d %H:%M')
print('当前时间',show_now_time)
end_time = now_time + timedelta(minutes = 1) # 这里就自己定义啦,这里是5分钟
# 参数看括号里面 class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
show_end_time = end_time.strftime('%Y-%m-%d %H:%M')
print('主进程将结束运行的时间',show_end_time)
child_process = None
running = False
while True:
now = datetime.now()
if now <= end_time:
running = True
else: # 到期了,该凉了
for num in range(10):
print('\r离程序的退出还剩%s秒'%(9-num),end='') # 来一个贴心的退出倒计时
sleep(1)
quit()
if running and child_process is None:
print('启动子GUI进程')
child_process = multiprocessing.Process(target=gui)
child_process.daemon = True # 多进程的守护进程设置方法,这样主进程一关,子进程必须凉
child_process.start()
sleep(1)
运行一下