如何将编译日期/时间放入窗口标题中? 以下示例(当然)将不起作用,因为它将在程序启动时将日期和时间放入标题中。 好吧,每次编译新版本时,我都可以在源代码中手动输入日期和时间。但是,我希望有一个智能且自动化的解决方案。有什么想法吗?
代码:
import sys
from datetime import datetime
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
class MyWindow(QWidget):
def __init__(self):
super(MyWindow,self).__init__()
self.setGeometry(100,100,400,200)
self.setWindowTitle('Version ' + datetime.now().strftime("%Y%m%d-%H%M"))
# define button1
self.button1 = QPushButton('Push me',self)
self.button1.move(100,100)
self.button1.setStyleSheet("background-color: #ddffdd")
self.button1.clicked.connect(self.button1_clicked)
def button1_clicked(self):
msg = QMessageBox()
msg.setText("This is a message box")
msg.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle("plastique")
window = MyWindow()
window.show()
sys.exit(app.exec_())
编译依据:
pyinstaller --onefile tbMinimalPyQt5.py
.spec文件
# -*- mode: python -*-
block_cipher = None
a = Analysis(['tbMinimalPyQt5.py'],
pathex=['C:\\User\\Test'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
name='tbMinimalPyQt5',
debug=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=True )
答案 0 :(得分:1)
一种解决方案是,在.spec中编写代码以创建带有数据的.py:
# -*- mode: python -*-
import datetime
data = {
"BUILD_DATE": datetime.datetime.now().strftime("%Y%m%d-%H%M")
}
with open('constants.py', 'w') as f:
for k, v in data.items():
f.write("{} = \"{}\"\n".format(k, v))
block_cipher = None
a = Analysis(['tbMinimalPyQt5.py'],
pathex=['C:\\User\\Test'],
# ...
然后在.py文件中,使用在编译时生成的值导入文件constants.py:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
import constants
class MyWindow(QWidget):
def __init__(self):
super(MyWindow,self).__init__()
self.setGeometry(100,100,400,200)
self.setWindowTitle('Version ' + constants.BUILD_DATE)
# define button1
self.button1 = QPushButton('Push me',self)
self.button1.move(100,100)
self.button1.setStyleSheet("background-color: #ddffdd")
self.button1.clicked.connect(self.button1_clicked)
def button1_clicked(self):
msg = QMessageBox()
msg.setText("This is a message box")
msg.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setStyle("plastique")
window = MyWindow()
window.show()
sys.exit(app.exec_())
最后,您使用.spec进行编译:
pyinstaller tbMinimalPyQt5.spec
答案 1 :(得分:0)
听起来您可以使用os.path.getmtime()
来获取EXE文件的时间戳,然后在窗口标题中报告该时间戳。唯一脆弱的部分是确保您拥有以绝对方式已知的EXE路径...
因此,您可以将上面的datetime.now().strftime("%Y%m%d-%H%M")
呼叫改为time.ctime(os.path.getmtime(EXEFILE))
。