首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用按钮重启Python GUI程序?

如何使用按钮重启Python GUI程序?
EN

Stack Overflow用户
提问于 2018-05-14 03:38:55
回答 1查看 1.3K关注 0票数 1
    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‘,并没有重新启动程序。

有没有人知道通过点击按钮重新启动程序的方法

EN

回答 1

Stack Overflow用户

发布于 2018-05-14 03:50:09

使用以下示例程序。它将关闭所有打开的文件和连接,这可能会导致内存问题。

然后,它将重新启动程序。

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!!!')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50319970

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档