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‘,并没有重新启动程序。
有没有人知道通过点击按钮重新启动程序的方法
发布于 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!!!')
https://stackoverflow.com/questions/50319970
复制相似问题