You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Tkinter按钮实现Python程序GUI重启功能

Python GUI重启按钮实现方法

核心思路

程序重启的本质是用新进程替换当前运行的进程,常用os.execv实现——它会终止当前进程并启动新的相同程序进程。


Tkinter 实现示例

import tkinter as tk
import os
import sys

def restart_app():
    # 关闭当前GUI窗口
    root.destroy()
    # 重启脚本:sys.executable是Python解释器路径,sys.argv保留启动参数
    os.execv(sys.executable, [sys.executable] + sys.argv)

# 创建主窗口
root = tk.Tk()
root.title("重启按钮示例")

# 添加重启按钮
restart_btn = tk.Button(root, text="重启程序", command=restart_app, padx=10, pady=5)
restart_btn.pack(pady=30)

root.mainloop()

PyQt5 实现示例

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
import sys
import os

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setup_ui()

    def setup_ui(self):
        self.setWindowTitle("重启按钮示例")
        self.setFixedSize(200, 120)
        
        # 创建重启按钮
        restart_btn = QPushButton("重启程序", self)
        restart_btn.clicked.connect(self.restart_app)
        restart_btn.move(50, 40)

    def restart_app(self):
        # 退出当前Qt应用
        QApplication.quit()
        # 重启进程
        os.execv(sys.executable, [sys.executable] + sys.argv)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

注意事项

  • 若程序有未保存的用户数据,重启前需添加数据保存逻辑,避免数据丢失。
  • 若程序被打包为可执行文件(如用PyInstaller),sys.executable会指向打包后的exe文件,无需额外修改路径。

内容的提问来源于stack exchange,提问作者fera fani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 22:45:26