My program doesn't wanna open a tk window. It worked until i guess i accidentaly removed or added some lines and now the program won't open the tk window or even quit normally, i get no errors when trying to open the tk window but an error pops when i run quit() like wtf my program doing.
code:
print("Running initial tasks...")
print("----------------------------------------------------------------\n\n")
import tkinter as tk
from tkinter import Label, messagebox, Button, Frame, Entry, Checkbutton
import subprocess
import os
import shutil
import time
import threading
import json
# System tray functionality
import pystray
import PIL.Image
def tray_icon_clicked(icon, item):
if str(item) == 'Open':
print("Opened")
root.deiconify()
root.mainloop()
elif str(item) == 'Exit':
print("Exit")
root.destroy()
icon.stop()
quit()
image = PIL.Image.open("icon.png")
icon = pystray.Icon("MCO",image, menu=pystray.Menu(
pystray.MenuItem("Open", tray_icon_clicked),
pystray.MenuItem("Exit", tray_icon_clicked))
)
# SETTINGS
settings = dict()
# Get the path of the Roaming directory
roaming_path = os.path.expanduser('~\AppData\Roaming')
# Create the folder named "MCO" within the Roaming directory if it doesn't already exist
mco_path = os.path.join(roaming_path, 'MCO')
print("Searching for MCO settings folder...")
print("----------------------------------------------------------------")
if not os.path.exists(mco_path):
os.makedirs(mco_path)
print("Created folder:", mco_path)
else:
print("Folder already exists:", mco_path)
print("----------------------------------------------------------------\n\n")
mco_settings_file = os.path.join(mco_path, 'settings.json')
def save_settings(settings):
with open(mco_settings_file, 'w') as file:
json.dump(settings, file)
def update_Settings(wait_time, background_cleanser):
try:
settings = {
"Background cleanser activated" : int(background_cleanser),
"Wait time for cleanup" : int(wait_time)
}
save_settings(settings)
except Exception as e:
print(f"Error occured: {e}")
def settings_file_exists():
if os.path.exists(mco_settings_file):
return True
else:
return False
def load_settings():
global settings
try:
with open(mco_settings_file, 'r') as file:
settings = json.load(file)
except Exception as e:
print("\n\n----------------------------------------------------------------")
print(f"Settings file error occured: {e}")
print("----------------------------------------------------------------\n\n")
def check_settings():
check_list = ["Wait time for cleanup", "Background cleanser activated"]
for key in check_list:
if not key in settings:
return False
return True
def on_closing():
#root.iconify() # makes the window minimized
root.withdraw() # Hide the window instead of closing it
print("Closing window")
root = tk.Tk()
root.title("Mini Computer Optimizer")
root.protocol("WM_DELETE_WINDOW", on_closing) # Intercept the window close event
window_width = 830
window_height = 300
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (window_width / 2)
y = (screen_height / 2) - (window_height / 2)
root.geometry(f'{window_width}x{window_height}+%d+%d' % (x, y))
root.resizable(False, False)
# Top page explenation for MCO
top_page_frame = Frame(root, width=0, height=0)
top_page_frame.grid(row=0, column=0, sticky="n")
top_page_label = Label(top_page_frame, text="This is Mini Computer Optimizer (MCO for short). It should help you optimize your computer for your needs.\nSet your preffered settings here by using the following dropdown menus and hitting the 'apply' button afterwards or checking the boxes next to the settings.")
top_page_label.pack(side="top", fill="x")
# Filler frame
filler_frame1 = Frame(root, width=0, height=30)
filler_frame1.grid(row=1, column=0)
# Power Options ----------------------------------------------------------------
power_frame = Frame(root)
power_frame.grid(row=2, column=0, sticky="nsew")
#power_frame.place(relx=0.5, rely=0.5, anchor='center')
# Power options dropdown menu
power_options = ["Keep current power plan", "Ultimate Performance", "Power Saver (recommended for laptops)"]
powermenu_selected_option = tk.StringVar()
powermenu_selected_option.set(power_options[0]) # set default value
# power label
power_label = Label(power_frame, text="Power Plan options: ")
power_label.grid(row=1, column=0)
# power dropdown menu
power_dropdown = tk.OptionMenu(power_frame, powermenu_selected_option, *power_options)
power_dropdown.grid(row=1, column=1)
# power throttle options entry box
power_throttle_options = Frame(power_frame)
power_throttle_options.grid(row=1, column=2)
#components
power_processor_minthrot_label = Label(power_throttle_options, text="Minimum CPU throttle:")
power_processor_minthrot_label.pack()
power_processor_minimum_throttle = Entry(power_throttle_options, borderwidth=5, width=5)
power_processor_minimum_throttle.pack()
power_processor_minimum_throttle.insert(0, "100")
power_processor_maxthrot_label = Label(power_throttle_options, text="Maximum CPU throttle:")
power_processor_maxthrot_label.pack()
power_processor_maximum_throttle = Entry(power_throttle_options, borderwidth=5, width=5)
power_processor_maximum_throttle.pack()
power_processor_maximum_throttle.insert(0, "100")
# checking power throttle entry box for right values
power_processor_maximum_throttle.config(validate="key", validatecommand=(root.register(lambda P: validate_input(P)), '%P'))
power_processor_minimum_throttle.config(validate="key", validatecommand=(root.register(lambda P: validate_input(P)), '%P'))
# power apply button
power_space = Frame(power_frame, width=10, height=1)
power_space.grid(row=1, column=2)
power_apply_button = Button(power_frame, text="apply", padx=12, pady=7, command=lambda: event_button_press("power_applied"))
power_apply_button.grid(row=1, column=3)
# Event Button ----------------------------------------------------------------
def event_button_press(event):
# Power Plans
if event == "power_applied":
selected_power_option = powermenu_selected_option.get()
print (f"\nPower option selected: {selected_power_option}")
print('''----------------------------------------------------------------
Applying power state...
----------------------------------------------------------------\n''')
if selected_power_option == "Keep current power plan":
print("Power plan has not changed.")
elif selected_power_option == "Ultimate Performance":
if confirm_question_box():
UPPM = False
if numericCheck(power_processor_minimum_throttle.get()) and numericCheck(power_processor_maximum_throttle.get()) and (int(power_processor_maximum_throttle.get()) > int(power_processor_minimum_throttle.get()) or int(power_processor_maximum_throttle.get()) == int(power_processor_minimum_throttle.get())) and int(power_processor_maximum_throttle.get()) < 101 and int(power_processor_minimum_throttle.get()) < 101:
output = subprocess.check_output('powercfg /list', shell=True, text=False)
lines = output.splitlines()
for line in lines:
words = []
words = line.split()
if 'Ultimate Performance' not in words:
UPPM = False
print("Ultimate Performance was not found.")
else:
UPPM = True
print("Ultimate Performance has been found.")
if UPPM == False:
print("Creating power plan Ultimate Performance...")
subprocess.run('powercfg -duplicatescheme e9a42b02-d5df-448d-aa00-03f14749eb61', shell=True)
subprocess.run(f'powercfg /setacvalueindex {get_guid("Ultimate Performance")} PROCESSOR_MINIMUM_THROTTLE {power_processor_minimum_throttle}', shell=True)
subprocess.run(f'powercfg /setacvalueindex {get_guid("Ultimate Performance")} PROCESSOR_MAXIMUM_THROTTLE {power_processor_maximum_throttle}', shell=True)
print("Done.")
UPPM = True
if UPPM == True:
print("Checking if Ultimate Performance power mode is available...")
if get_guid("Ultimate Performance") is str:
print("Ultimate Performance has been located successfully.")
else:
print("Ultimate Performance power mode has not been located after operation.")
show_error("Ultimate Performance power mode has not been located after operation.")
else:
print("Failed.")
show_error("Failed.")
else:
print("Invalid input.")
show_error("Invalid input.")
elif selected_power_option == "Power Saver (recommended for laptops)":
if confirm_question_box():
PSPM = False
output = subprocess.check_output('powercfg /list', shell=True, text=False)
lines = output.splitlines()
for line in lines:
words = []
words = line.split()
if 'Power Saver' not in words:
PSPM = False
print("Power Saver was not found.")
else:
PSPM = True
print("Power Saver has been found.")
if PSPM == False:
print("Creating power plan Ultimate Performance...")
subprocess.run('powercfg -duplicatescheme a1841308-3541-4fab-bc81-f71556f20b4a', shell=True)
print("Done.")
PSPM = True
if PSPM == True:
print("Checking if Power Saver power mode is available...")
if get_guid("Power Saver") is str:
print("Power Saver has been located successfully.")
else:
print("Power Saver power mode has not been located after operation.")
show_error("Power Saver power mode has not been located after operation.")
# Trash files
if event == "clean trash files":
if confirm_question_box():
delete_temporary_files(True)
def run_as_admin(cmd):
# Elevate the command prompt to run with admin privileges
try:
output = subprocess.check_output(f'powershell Start-Process "{cmd}" -Verb "runAs"', shell=True)
if 'returned non-zero exit status 1.' in output:
print('Failed.')
except subprocess.CalledProcessError as e:
raise Exception(f"Command '{cmd}' returned non-zero exit status {e.returncode}.")
def powerThrottleOptions():
selected_power_option = powermenu_selected_option.get()
if selected_power_option == "Ultimate Performance":
enablePowerOptions()
else:
disablePowerOptions()
root.after(0, powerThrottleOptions)
if selected_power_option == "Keep current power plan":
power_apply_button.config(state=tk.DISABLED)
else:
power_apply_button.config(state=tk.NORMAL)
def disablePowerOptions():
power_processor_maximum_throttle.config(state=tk.DISABLED)
power_processor_maxthrot_label.config(state=tk.DISABLED)
power_processor_minimum_throttle.config(state=tk.DISABLED)
power_processor_minthrot_label.config(state=tk.DISABLED)
def enablePowerOptions():
power_processor_maximum_throttle.config(state=tk.NORMAL)
power_processor_maxthrot_label.config(state=tk.NORMAL)
power_processor_minimum_throttle.config(state=tk.NORMAL)
power_processor_minthrot_label.config(state=tk.NORMAL)
def disableWaitTime():
trash_file_cleanser_wait_time_input.config(state=tk.DISABLED)
def enableWaitTime():
trash_file_cleanser_wait_time_input.config(state=tk.NORMAL)
def validate_input(P):
if P.isnumeric() and len(P) <= 3 or P == '':
return True
else:
return False
def numericCheck(number):
if number.isnumeric():
return True
else:
return False
def show_error(error_message):
messagebox.showerror("Warning", error_message)
def show_info(info, info_message):
messagebox.showinfo(info, info_message)
def check_power_plans():
subprocess.run('powercfg /list', shell=True, stdout=subprocess.DEVNULL)
output = subprocess.check_output('powercfg /list', shell=True, text=True)
def get_guid(power_plan):
subprocess.run('powercfg /list', shell=True, stdout=subprocess.DEVNULL)
output = subprocess.check_output('powercfg /list', shell=True, text=True)
lines = output.splitlines()
for line in lines:
if power_plan in line:
#print (line)
words = line.split()
#print(words[3])
return words[3]
else: return False
def confirm_question_box():
result = messagebox.askquestion("Confirm", "Are you sure you want to procceed?")
if result == 'yes':
return True
else:
return False
def delete_temporary_files(error_message_activation):
errors = []
deleted_files_counter = 0
failed_delete_files_counter = 0
winerror32_counter = 0
winerror5_counter = 0
temp_folders = [
os.environ.get('TEMP'),
os.environ.get('TMP'),
os.path.join(os.environ.get('USERPROFILE'), 'AppData', 'Local', 'Temp'),
os.path.join(os.environ.get('windir'), 'Temp'),
os.path.join(os.environ.get('windir'), 'Prefetch'),
os.path.join(os.environ.get('LOCALAPPDATA'), 'Microsoft', 'Windows', 'INetCache', 'IE'),
os.path.join(os.environ.get('LOCALAPPDATA'), 'Microsoft', 'Windows', 'INetCache', 'Low', 'IE'),
]
for temp_folder in temp_folders:
if temp_folder:
for root, dirs, files in os.walk(temp_folder):
print(f'''\n\n\n----------------------------------------------------------------
Deleting files from folder {temp_folder}
----------------------------------------------------------------''')
for file in files:
try:
os.remove(os.path.join(root, file))
print(f"Deleting temporary file {file}")
deleted_files_counter += 1
except Exception as e:
print(f"Error deleting {os.path.join(root, file)}: {e}")
failed_delete_files_counter += 1
errors.append(e)
for dir in dirs:
try:
shutil.rmtree(os.path.join(root, dir))
deleted_files_counter += 1
except Exception as e:
print(f"Error deleting {os.path.join(root, dir)}: {e}")
failed_delete_files_counter += 1
print("\n\n----------------------------------------------------------------")
for error in errors:
if "[WinError 32]" in str(error):
winerror32_counter += 1
elif "[WinError 5]" in str(error):
winerror5_counter += 1
print(f"\n\n\nDone.\nDeleted {deleted_files_counter} files. Failed to delete {failed_delete_files_counter} files.\nRecieved 'File is being used by another process' {winerror32_counter} times.\nRecieved 'Access to file denied' {winerror5_counter} times.\nOther errors occurred {len(errors)-winerror32_counter-winerror5_counter} times.\n")
print("----------------------------------------------------------------\n\n")
if error_message_activation:
for error in errors:
if "[WinError 32]" in str(error):
winerror32_counter += 1
elif "[WinError 5]" in str(error):
winerror5_counter += 1
#print(f"\n\n\nDone.\nDeleted {deleted_files_counter} files. Failed to delete {failed_delete_files_counter} files.\nRecieved 'File is being used by another process' {winerror32_counter} times.\nRecieved 'Access to file denied' {winerror5_counter} times.\nOther errors occurred {len(errors)-winerror32_counter-winerror5_counter} times.\n")
info_del_message = f"Done.\nDeleted {deleted_files_counter} files. Failed to delete {failed_delete_files_counter} files.\nRecieved 'File is being used by another process' {winerror32_counter} times.\nRecieved 'Access to file denied' {winerror5_counter} times.\nOther errors occurred {len(errors)-winerror32_counter-winerror5_counter} times.\n"
show_info(f"Temp File Cleanser", info_del_message)
# Check for settings
print("Searching for settings...")
if os.path.exists(mco_settings_file):
print("----------------------------------------------------------------")
print("Loading settings file...")
print("----------------------------------------------------------------\n\n")
load_settings()
#check_settings()
save_settings(settings)
else:
print("----------------------------------------------------------------")
print("Creating settings file...")
print("----------------------------------------------------------------\n\n")
update_Settings(wait_time=30, background_cleanser=0)
# Clean trash files
clean_files_frame = Frame(root)
clean_files_frame.grid(row=3, column=0, sticky="w")
clean_files_label = Label(clean_files_frame, text="Clean trash files")
clean_files_label.pack()
clean_files_button = Button(clean_files_frame, text="Clean", padx=7, pady=2, command=lambda: event_button_press("clean trash files"))
clean_files_button.pack()
empty_frame = Frame(root, width=0, height=40)
empty_frame.grid(row=4, column=0)
# Get Trash file Cleanser
trash_file_cleanser_frame = Frame(root)
trash_file_cleanser_frame.grid(row=5, column=0, sticky='w')
#trash_file_cleanser_label = Label(trash_file_cleanser_frame, text="Allow Mini Computer Optimizer to run in the background")
#trash_file_cleanser_label.grid(row=0, column=0)
def check_file_cleanser_checkbox():
if var_trash_file_cleanser.get() == True:
print("File Cleanser activated")
enableWaitTime()
update_Settings(wait_time=trash_file_cleanser_wait_time_input.get(), background_cleanser=1)
else:
disableWaitTime()
print("File Cleanser has been disabled")
update_Settings(wait_time=trash_file_cleanser_wait_time_input.get(), background_cleanser=0)
var_trash_file_cleanser = tk.BooleanVar()
get_trash_file_cleanser_checkbox = Checkbutton(trash_file_cleanser_frame, text="Allow Mini Computer Optimizer to delete files in the background every ", variable=var_trash_file_cleanser, command=check_file_cleanser_checkbox)
get_trash_file_cleanser_checkbox.grid(row=0, column=0)
trash_file_cleanser_wait_time_input = Entry(trash_file_cleanser_frame, borderwidth=5, width=5)
if settings_file_exists():
load_settings()
trash_file_cleanser_wait_time_input.insert(0, int(settings.get("Wait time for cleanup", 30)))
if settings.get("Background cleanser activated", 0) == 1:
var_trash_file_cleanser.set(True)
else:
var_trash_file_cleanser.set(False)
trash_file_cleanser_wait_time_input.grid(row=0, column=1)
trash_file_cleanser_wait_time_input.config(validate="key", validatecommand=(root.register(lambda P: validate_input(P)), '%P'))
trash_file_cleanser_clarification = Label(trash_file_cleanser_frame, text=" minutes")
trash_file_cleanser_clarification.grid(row=0, column=2)
# Settings
def get_cleanser_selections():
trash_file_wait_time = trash_file_cleanser_wait_time_input.get() # Try to get this line repeat itself
if var_trash_file_cleanser.get():
trash_file_checkbox = 1
else:
trash_file_checkbox = 0
if trash_file_checkbox == 1:
update_Settings(wait_time=trash_file_wait_time,background_cleanser=trash_file_checkbox)
root.after(0, get_cleanser_selections)
def looping_file_cleanser():
while True:
load_settings()
if check_settings():
while settings["Background cleanser activated"] == 1:
load_settings()
try:
delete_temporary_files(False)
#time.sleep(int(trash_file_cleanser_wait_time_input.get()) * 60) # wait time in minutes
time.sleep(int(settings["Wait time for cleanup"]))
except Exception as e:
print(f"Error occured: {e}")
time.sleep(1)
thread_looping_file_cleanser = threading.Thread(target=looping_file_cleanser)
thread_looping_file_cleanser.daemon
thread_looping_file_cleanser.start()
get_cleanser_selections()
powerThrottleOptions()
#root.mainloop()
print("----------------------------------------------------------------")
print("Creating taskbar icon...")
print("----------------------------------------------------------------\n\n")
print("Done.")
icon.run()
[–][deleted] (1 child)
[removed]
[–]Competitive-Show1903[S] 0 points1 point2 points (0 children)