首页 > 解决方案 > 如果我关闭应用程序,如何取消计时器或停止

问题描述

我试图做一个选择器在模拟器上运行不同的配置,我放了一个计时器来关闭这个应用程序并运行默认选项。

我的问题是当我运行应用程序并在没有选择的情况下关闭它时,计时器会继续并且不会停止,并且在时间结束后运行另一个应用程序。

import os
import threading 
#import shutil
import tkinter as tk
from tkinter import *

def drivers(driver1, driver2):
    wait_time.cancel()  
    ra_config = open("F:\\Games\\RetroArch\\retroarch.cfg", "rt")
    temp_data = ra_config.read()
    temp_data = temp_data.replace('video_driver = "' + driver1 + '"', 'video_driver = "' + driver2 + '"')
    ra_config.close()
    ra_config = open("F:\\Games\\RetroArch\\retroarch.cfg", "wt")
    ra_config.write(temp_data)
    ra_config.close()
    os.startfile (r"F:\\Games\\RetroArch\\retroarch.exe")
    root.quit()

HEIGHT = 200
WIDTH = 700

root = tk.Tk()
root.title("Choose one")

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

x_coordinate = (screen_width/2) - (WIDTH/2)
y_coordinate = (screen_height/2) - (HEIGHT/2)

root.geometry ("%dx%d+%d+%d" % (WIDTH, HEIGHT, x_coordinate, y_coordinate))

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

photo_vul = PhotoImage(file = r"img\\vulkan.png") 
photo_gl = PhotoImage(file = r"img\\opengl.png")
photo_icon = PhotoImage(file = r"img\\retroarch-icon.png") 

root.iconphoto(False, photo_icon)

#frame = tk.Frame(root, highlightbackground='black', highlightthickness=1, bd=10)
frame = tk.Frame(root, bd=10)
frame.place(relx = 0.5, rely=0.5, relwidth=0.95, relheight=0.95, anchor="c")

button = tk.Button(frame, bg='white', activebackground='white', image = photo_vul, font=60, command=lambda: drivers("glcore", "vulkan"))
button.place(relx = 0.05, relwidth=0.4, relheight=1)

button2 = tk.Button(frame, bg='#0277bd', activebackground='#0277bd', image = photo_gl, font=60, command=lambda: drivers("vulkan", "glcore"))
button2.place(relx = 0.55, relwidth=0.4, relheight=1)

#create the vulkan config if the orig
#og = r"F:\\Games\\RetroArch\\retroarch.cfg"
#tg = r"F:\\Games\\RetroArch\\retroarch-vulkan.cfg"
#shutil.copyfile(og, tg)

#pyinstaller --noconsole --onefile RApicker.py

wait_time = threading.Timer(15.0, drivers,["vulkan", "glcore"]).start()

root.mainloop()

标签: pythontimer

解决方案


在窗口删除

def delete_window():
    # Stop timer here

root.protocol("WM_DELETE_WINDOW", delete_window)
root.mainloop()

销毁时

def destroy():
    # Stop timer here

root.bind("<Destroy>", destroy)
root.mainloop()

推荐阅读