按照楼上两位的回复实际验证了一下,pywin32实际引入的应该是win32console部分,而且GetConsoleWindow()和ShowWindow函数不要加在开头,但是打包之后还有控制台窗口,不知道是不是使用方式不对。
第二个,使用的ctypes模块,直接贴一下楼主的范例代码修改版
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import os
import tkinter as tk
import ctypes
whnd = ctypes.windll.kernel32.GetConsoleWindow()
if whnd != 0:
ctypes.windll.user32.ShowWindow(whnd, 0)
ctypes.windll.kernel32.CloseHandle(whnd)
import ctypes
whnd = ctypes.windll.kernel32.GetConsoleWindow()
if whnd != 0:
ctypes.windll.user32.ShowWindow(whnd, 0)
ctypes.windll.kernel32.CloseHandle(whnd)
hostName = socket.gethostname()
# execute command, and return the output
def execCmd(cmd):
r = os.popen(cmd)
text = r.read()
r.close()
return text
def usrname():
cmd = "echo %username%"
uname = execCmd(cmd)
user = uname.split()
return user[0]
##########GUI##########
window = tk.Tk()
window.title('用户信息获取')
window.geometry('350x150')
user_var_lebel = tk.StringVar()
user_var = tk.StringVar()
host_var_lebel = tk.StringVar()
host_var = tk.StringVar()
###########
user_var_lebel.set('用户名:')
user_var.set(usrname())
host_var_lebel.set('主机名:')
host_var.set(hostName)
###########
# 用户名标签
user_lebel = tk.Label(window, textvariable=user_var_lebel, bg='DarkGray', fg='White', font=('Arial',10,"bold"), width=9,
height=2).place(x=10, y=10)
# 用户名系显示
username = tk.Label(window, textvariable=user_var, bg='DarkGray', fg='black', font=('Arial', 10), width=30, height=2).place(
x=95, y=10)
# 主机名标签
host_lebel = tk.Label(window, textvariable=host_var_lebel, bg='DarkGray', fg='White', font=('Arial', 10,"bold"), width=9,
height=2).place(x=10, y=60)
# 主机名显示
hostname = tk.Label(window, textvariable=host_var, bg='DarkGray', fg='black', font=('Arial', 10), width=30,
height=2).place(x=95, y=60)
window.mainloop()
这个是可行的,但是控制台还是会一闪而过。
另外说一句,用pyinstaller打包时候,加-w我是会报错的,所以一般打包指令我用的都是pyinstaller -F xxx.py。不然总会出Failed to execute script xxx的报错。相关资料在gitpyinstaller报错资料