0%

用PyQt GUI写桌面程序

尝试用PYQT写了个windows桌面程序,每次启动时向服务器获取最新的配置信息,更新桌面背景,并检测本地的补丁版本,如果服务端有新的补丁则可以选择更新。

《一》PyQt4安装: https://qa.debian.org/watch/sf.php/pyqt/

注意安装的python是32还是64的,要下对应的版本。

《二》使用PyQt4 designer构建界面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# -*-coding:utf-8-*-

"""
In this example, we determine the event sender
object.
"""

import sys,time,os,json,requests
import webbrowser

from PyQt4 import QtGui,QtCore
from PyQt4.QtCore import QByteArray
from PyQt4.QtCore import QSize
from PyQt4.QtCore import Qt,QString
from PyQt4.QtGui import QListWidget
from PyQt4.QtGui import QMessageBox
from PyQt4.QtGui import QApplication, QLabel, QMovie, QPainter, QFontMetrics
import urllib
from PyQt4.QtGui import QSizePolicy
from PyQt4.QtGui import QVBoxLayout
from PyQt4.QtGui import QWidget


class myListWidget(QListWidget):

def Clicked(self,item):
QMessageBox.information(self, "ListWidget", "You clicked: "+item.text())

class Example(QWidget):

def __init__(self, parent=None):
QWidget.__init__(self, parent)
# 写入初始配置
if os.path.exists('plugins.txt') == False:
savefile = open("plugins.txt", 'w')
savefile.writelines('{"pluginsVersion": 0}')
savefile.close()
try:
base_url = 'http://ownerworld.win:5000/getconf'
Response = requests.get(base_url)
self.server_data = json.loads(Response.content)
except:
self.server_data = {
"code": 0,
"backGroundImg":"http://cdn.orion-c.top/lul.jpg",
"backgroundType":"jpg",
"serviceData":[],
"plugins":[{
"pluginsVersion":1,
"pluginsVersionLink":"http://ownerworld.win:8081/patch-zhCN-5.mpq",
"pluginsVersionPath":"Data/zhCN/patch-zhCN-5.mpq",
"pluginsType":"mpq"
}],
"host":"i_know_who_u_are"
}

self.initUI()

def initUI(self):
# 初始化position
self.m_DragPosition = self.pos()
self.resize(900, 600)
self.center()
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.setMouseTracking(True)
self.setStyleSheet("background-color:white;")

if self.server_data["backgroundType"] == "gif":
#加载动图
self.movie_screen = QLabel()
#self.movie_screen.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
self.movie_screen.setAlignment(Qt.AlignCenter)
main_layout = QVBoxLayout()
main_layout.addWidget(self.movie_screen)
self.setLayout(main_layout)
if os.path.exists("backgroud.gif"):
os.system('del backgroud.gif')
urllib.urlretrieve(self.server_data["backGroundImg"],
"backgroud.gif",self.downback)
self.movie = QMovie("backgroud.gif", QByteArray(), self)
self.movie.setCacheMode(QMovie.CacheAll)
self.movie.setSpeed(100)
self.movie_screen.setMovie(self.movie)
self.movie.start()
else:
# 加载网络图片
image_lbl1 = QtGui.QLabel(u"", self)
url = self.server_data["backGroundImg"]
Response = requests.get(url, stream=True)
image_data = Response.content
image = QtGui.QImage()
image.loadFromData(image_data)
image_lbl1.setPixmap(QtGui.QPixmap(image))
image_lbl1.resize(900,600)
image_lbl1.setStyleSheet("""
QLabel{
width:900px;
height:600px;
text-align:center;
}
""")

#公告
self.item_data = self.server_data["serviceData"]
item_list = []
for item in self.item_data:
item_list.append(item["name"])
if len(item_list)>0:
list_title = QtGui.QLabel(u'公告信息',self)
list_title.setGeometry(620,30,280,25)
list_title.setStyleSheet("""
QLabel{
color:#f8b700;
margin-left:5px;
font-size:20px;
font-weight:bold;
background:rgba(0,0,0,0.6);
}
""")
listWidget = QtGui.QListWidget(self)
listWidget.setGeometry(600,60,270,200)
listWidget.addItems(item_list);
listWidget.itemClicked.connect(self.Clicked)
listWidget.setStyleSheet(
"""
QListWidget
{
border:0px solid gray; /*边界线:宽度、颜色*/
background:rgba(0,0,0,0.6); /*表格背景色*/
color:#f8b700; /*前景色:文字颜色*/
/*margin:5px,5px,0px,50px;*/ /*上、下、左、右,间距*/
font-size:15px;

}

/*
QListWidget::item
{
padding-top:24px;
padding-bottom:4px;
}
*/

QListWidget::item:hover
{
show-decoration-selected:5;
background:skyblue;
}

QListWidget::item:selected
{
/*border:0px;*/
background:lightgray;
padding:0px;
margin:0px;
color:red;
}

/*上次选择后保留的状态,鼠标离开后显示*/
QListWidget::item:selected:!active
{
border-width:0px;
background:lightgreen;
}

QScrollBar:vertical
{
width:8px;
background:rgb(0,0,0,0%);
margin:0px,0px,0px,0px;
padding-top:12px; /*上预留位置*/
padding-bottom:12px; /*下预留位置*/
}
QScrollBar::handle:vertical
{
width:8px;
background:rgb(0,0,0,25%);
border-radius:4px;
min-height:20px;
}
QScrollBar::handle:vertical:hover
{
width:9px;
background:rgb(0,0,0,50%);
border-radius:4px;
min-height:20;
}

/*设置下箭头*/
QScrollBar::add-line:vertical
{
height:12px;
width:10px;
border-image:url(:/selectfile/scroll/3.png);
subcontrol-position:bottom;
}

/*设置上箭头*/
QScrollBar::sub-line:vertical
{
height:12px;
width:10px;
border-image:url(:/selectfile/scroll/1.png);
subcontrol-position:top;
}

/*设置下箭头:悬浮状态*/
QScrollBar::add-line:vertical:hover
{
height:12px;
width:10px;
border-image:url(:/selectfile/scroll/4.png);
subcontrol-position:bottom;
}

/*设置上箭头:悬浮状态*/
QScrollBar::sub-line:vertical:hover
{
height:12px;
width:10px;
border-image:url(:/selectfile/scroll/2.png);
subcontrol-position:top;
}

/*当滚动条滚动的时候,上面的部分和下面的部分*/
QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical
{
background:rgb(0,0,0,10%);
border-radius:4px;
}
""")

# 检查跟新
self.checkUpate()

# 按钮
qbtn_close = QtGui.QPushButton(u"运行游戏", self)
qbtn_close.setGeometry(740, 490, 120, 50)
qbtn_close.setStyleSheet("QPushButton{background-color:#d60000;border:1px solid #000;font-family:Microsoft YaHei;color:#ffffff;font-size:20px;border-radius:5px;}"
"QPushButton:hover{background-color:rgb(234, 48, 18);}")
qbtn_close.clicked.connect(self.buttonClicked)
self.setWindowTitle(u'简单魔兽')
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("wow.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.setWindowIcon(icon)
#self.setWindowFlags(QtCore.Qt.Widget)
self.show()

def downback(self,a, b, c):
return

def Clicked(self,item):
#QMessageBox.information(self, "ListWidget", "You clicked: " + item.text())
self.webbrowser(item.text())

def setMovie(self, movie):
QLabel.setMovie(self, movie)
s = movie.currentImage().size()
self._movieWidth = s.width()
self._movieHeight = s.height()

# 支持窗口拖动,重写两个方法
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.m_drag = True
self.m_DragPosition = event.globalPos() - self.pos()
event.accept()
def mouseMoveEvent(self, QMouseEvent):
if QMouseEvent.buttons() and Qt.LeftButton:
self.move(QMouseEvent.globalPos() - self.m_DragPosition)
QMouseEvent.accept()
def mouseReleaseEvent(self, QMouseEvent):
self.m_drag = False

# 居中
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())

#浏览器打开
def webbrowser(self,item_name):
itemData = self.item_data
for item in itemData:
# QString互转
Str = unicode(QString(item_name))
if item['name'] == Str:
webbrowser.open(item["link"])

# 检测更新
def checkUpate(self):
plugins_file = open('plugins.txt')
plugins_data = plugins_file.read()
history_version = json.loads(plugins_data)
for plugins in self.server_data["plugins"]:
if history_version["pluginsVersion"] < plugins["pluginsVersion"]:
# 更新按钮
self.qbtn_update = QtGui.QPushButton(u"更新补丁", self)
self.qbtn_update.setGeometry(600, 490, 120, 50)
self.qbtn_update.setStyleSheet(
"QPushButton{background-color:#d60000;border:1px solid #000;color:#ffffff;font-size:20px;border-radius:5px;font-family:Microsoft YaHei;}"
"QPushButton:hover{background-color:rgb(234, 48, 18);}")
self.qbtn_update.clicked.connect(self.buttonClicked)
self.pbar = QtGui.QProgressBar(self)
self.pbar.setGeometry(30, 495, 540, 0)
self.pbar.setStyleSheet("""QProgressBar { border: 2px solid grey; border-radius: 5px; background-color: #FFFFFF;}QProgressBar::chunk { background-color: #00aeff; width: 20px;}QProgressBar { border: 2px solid grey; border-radius: 5px; text-align: center;}""")
self.netSpeed = QtGui.QLabel(u'下载速度:',self)
self.netSpeed.setGeometry(480,520,120,0)
self.netSpeed.setStyleSheet("""QLabel{background:rgba(0,0,0,0.6);color:green}""")
plugins_file.close()

# 运行按钮点击事件
def buttonClicked(self):
sender = self.sender()
if sender.text() == u"运行游戏":
if os.path.exists("wow.exe"):
self.statusBar().showMessage(sender.text() + ' was pressed, will be close in 1s')
time.sleep(1)
host = self.server_data["host"]
self.replaceRealmlist(host)
self.close()
else:
QMessageBox.warning(self, u"警告", u"未找到‘wow.exe’启动应用,请确认‘简单魔兽.exe’在游戏根目录!")
elif sender.text() == u"更新补丁":
if self.server_data["plugins"][0]["pluginsType"] == 'mpq':
self.pbar.resize(540, 35)
self.netSpeed.resize(120,50)
self.start_time = time.time()
try:
urllib.urlretrieve(self.server_data["plugins"][0]["pluginsVersionLink"], self.server_data["plugins"][0]["pluginsVersionPath"], self.Schedule)
except:
self.netSpeed.setText(u"下载失败!")
self.netSpeed.setStyleSheet("""QLabel{background:rgba(0,0,0,0.6);color:red}""")
if self.server_data["plugins"][0]["pluginsType"] == 'link':
if os.path.exists(self.server_data["plugins"][0]["pluginsVersionPath"]):
QMessageBox.information(self, u"补丁下载", u"您已下载,无需关注~")
else:
#self.box = QMessageBox.information(self, u"补丁下载", u"您有一份百度网盘补丁需要下载,如已经下载无需关注!",QMessageBox.Yes | QMessageBox.No)
button = QMessageBox.warning(self, u"补丁下载",u"您有一份百度网盘补丁需要下载,如已经下载请确认补丁位置正确!!",QMessageBox.Save | QMessageBox.Cancel,QMessageBox.Save)
if button == QMessageBox.Save:
webbrowser.open(self.server_data["plugins"][0]["pluginsVersionLink"])
else:
return

def Schedule(self,a, b, c):
'''
a:已经下载的数据块
b:数据块的大小
c:远程文件的大小
'''
speed = (a * b) / (time.time() - self.start_time)
down_size = float(a * b)
total_size = float(c)
bai = round(down_size / total_size * 100,0)
self.pbar.setValue(bai)
if bai == 100:
self.qbtn_update.setText(u'更新完成')
self.qbtn_update.setStyleSheet(
"QPushButton{background-color:grey;border:1px solid #000;color:#ffffff;font-size:20px;border-radius:5px;}")
self.pbar.resize(540, 0)
self.netSpeed.resize(120,0)
savefile = open("plugins.txt", 'w')
savefile.writelines('{"pluginsVersion": %d}'%self.server_data["plugins"][0]["pluginsVersion"])
savefile.close()
speed = u"下载速度:%d Mb/s" % round(speed / 1024, 2)
self.netSpeed.setText(speed)

#修改配置文件
def replaceRealmlist(self,host):
os.system('echo y | rd /s "Cache"')
os.system('echo SET realmlist "%s" > Data\zhTW\realmlist.wtf'%host)
os.system('echo SET realmlist "%s" > Data\enTW\realmlist.wtf'%host)
os.system('echo SET realmlist "%s" > Data\zhCN\realmlist.wtf'%host)
os.system('echo SET realmlist "%s" > Data\enCN\realmlist.wtf'%host)
os.system('echo SET realmlist "%s" > Data\enUS\realmlist.wtf'%host)
os.system('echo SET realmlist "%s" > realmlist.wtf'%host)
os.startfile("wow.exe")

def get_FileSize(filePath):
filePath = unicode(filePath, 'utf8')
fsize = os.path.getsize(filePath)
fsize = fsize / float(1024)
return int(fsize)

def main():

app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())


if __name__ == '__main__':
main()

《三》将写好的pyqt打包成exe:

压缩加壳需要先安装UPX:https://sourceforge.net/projects/upx/files/upx/3.91/

1
$ pyinstaller.exe  -w -F --icon=wow.ico --upx-dir=C:\Users\test\Downloads\upx391w\upx391w\upx.exe go.py