如何基于按钮点击无条件重新运行python程序? [英] How to unconditionally re-run a python program based on button click?

查看:40
本文介绍了如何基于按钮点击无条件重新运行python程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序执行结束时,我希望出现一个弹出消息,其中有一个可以重新运行程序的按钮.显然,我将设置一个按钮在单击时调用的函数,例如

At the end of my program execution, I want a popup message to appear that has a button which can re-run a program. Obviously, I will have setup a function that the button calls when it is clicked, as such

def restart():
    **python command that makes the whole program restart**

然后我会将此功能附加到以下按钮:

Then I would attach this function to the following button:

B1 = ttk.Button(popup, text='Restart program', width=17, command=lambda: restart())

有这样的命令吗?

快速说明:我找到了一个答案,但它不起作用,这里是:

Quick note:I found an answer but it doesn't work, here it is:

os.execl(sys.executable, sys.executable, *sys.argv)

推荐答案

我建议您使用 subprocess 模块重新执行旨在替换旧 os 的程序.exec...() 函数组.

I suggest that you use the subprocess module to re-execute the program which was designed to replace the older os.exec...() group of functions.

这是一个如何使用它重新启动脚本的可运行(即完整)示例,该示例已在使用 Python 3.6.4 的 Windows 上进行了测试:

Here's a runnable (i.e. complete) example of how to use it to restart the script, which was tested on Windows with Python 3.6.4:

import os
import subprocess
import sys
import tkinter as tk
import traceback

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack(fill="none", expand=True)  # Center the button.
        self.create_widgets()

    def create_widgets(self):
        self.restart_btn = tk.Button(self, text='Restart', command=self.restart)
        self.restart_btn.grid()

    def restart(self):
        command = '"{}" "{}" "{}"'.format(
            sys.executable,             # Python interpreter
            __file__,                   # argv[0] - this file
            os.path.basename(__file__), # argv[1] - this file without path
        )
        try:
            subprocess.Popen(command)
        except Exception:
            traceback.print_exc()
            sys.exit('fatal error occurred rerunning script')
        else:
            self.quit()


app = Application()
app.master.title('Restartable application')
app.mainloop()

这篇关于如何基于按钮点击无条件重新运行python程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆