如何使用按钮重新启动PythonGUI程序?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (260)
    restartButton = ttk.Button(text = "RESTART?", command = restartProgram)
    restartButton.place(x = 400, y = 100, width = 200, height = 40)

def restartProgram():
    os.execl(sys.executable, os.path.abspath('Game.py'), *sys.argv) 

这是我在重新启动程序时能找到的最接近的代码。但是,这段代码只打开了“Shell”,但没有重新启动程序。

有人知道通过单击按钮重新启动程序的方法吗?

提问于
用户回答回答于

在以下代码中,它将关闭所有打开的文件和连接,可能会导致内存问题,然后它将重新启动程序。

import os
import sys
import psutil
import logging

def restart_program():
    """Restarts the current program, with file objects and descriptors
       cleanup
    """

    try:
        p = psutil.Process(os.getpid())
        for handler in p.get_open_files() + p.connections():
            os.close(handler.fd)
    except Exception, e:
        logging.error(e)

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

请试试下面的代码。在Ubuntu 18.04上测试。

from Tkinter import *
import os
import sys
import psutil
import logging

def button_click():
    """ handle button click event and output text from entry area"""
    print('hello, submit button is clicked')    
    # do here whatever you want

def restart_program():
    """Restarts the current program, with file objects and descriptors cleanup"""
    try:
        p = psutil.Process(os.getpid())
        for handler in p.get_open_files() + p.connections():
            os.close(handler.fd)
    except Exception, e:
        logging.error(e)

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


def create_gui_app(label_title='Hello, How are you?'):
    window = Tk()
    window.title("Welcome to LikeGeeks app")
    lbl = Label(window, text=label_title)
    lbl.grid(column=0, row=0)

    submit_button = Button(window, command=button_click, text="Submit")
    submit_button.grid()
    restart_button = Button(window, command=restart_program, text="Restart")
    restart_button.grid()
    window.mainloop()

if __name__=='__main__':
    if len(sys.argv) > 1:
        create_gui_app(sys.argv[1])
    else:
        create_gui_app('No Argument Supplied!!!')

扫码关注云+社区

领取腾讯云代金券