I'm trying to make a "auto clicker" button that adds a value every second. This means I want the function to rerun to itself after waiting a second.
Although in customtkinter time.sleep() does not work, and I've seen that you can use the "after" function in tkinter, but I am unable to get it to work with customtkinter.
import cutomtkinter
import time
count = 0
autoclick_value = 1.
class ButtonWindow(customtkinter.CTkFrame):
def __init__(self, master):
global count
super().__init__(master)
def auto_click():
global count
global autoclick_value
count += autoclick_value
self.click_display.configure(text=f"You have " + str(round(count, 2)) + " clicks")
time.sleep(1)
def click_counter():
global count
auto_click()
count += click_power
self.click_display.configure(text=f"You have " + str(round(count, 2)) + " clicks")
self.click_display = customtkinter.CTkLabel(self, text="You have " + str(round(count, 2)) + " clicks.")
self.click_display.grid(row=0, column=0)
self.Button = customtkinter.CTkButton(self, text="Click me", command=click_counter)
self.Button.grid(row=1, column=0)
The time.sleep()
function doesn't work with customtkinter because it freezes the thread the application is running in. To overcome this problem, you should use, as you have seen, the after()
method. This method calls a function after a given amount of time and does not freeze the application.
To use this method, you should replace the time.sleep(1)
line by master.after(1000, auto_click)
.
Your full code is now:
import customtkinter
count = 0
click_power = 1
autoclick_value = 1.
class ButtonWindow(customtkinter.CTkFrame):
def __init__(self, master):
global count
super().__init__(master)
def auto_click():
global count
global autoclick_value
count += autoclick_value
self.click_display.configure(text=f"You have " + str(round(count, 2)) + " clicks")
master.after(1000, auto_click)
def click_counter():
global count
auto_click()
count += click_power
self.click_display.configure(text=f"You have " + str(round(count, 2)) + " clicks")
self.click_display = customtkinter.CTkLabel(self, text="You have " + str(round(count, 2)) + " clicks.")
self.click_display.grid(row=0, column=0)
self.Button = customtkinter.CTkButton(self, text="Click me", command=click_counter)
self.Button.grid(row=1, column=0)
Hope I helped you, have a nice day