gpt4 book ai didi

python - 如何使用按钮重新启动Python GUI程序?

转载 作者:行者123 更新时间:2023-12-01 09:26:51 25 4
gpt4 key购买 nike

    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!!!')

关于python - 如何使用按钮重新启动Python GUI程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50319970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com