CustomTKinter 中的 Time.sleep()

问题描述 投票:0回答:1

我正在尝试制作一个“自动点击器”按钮,每秒都会添加一个值。 这意味着我希望该函数在等待一秒钟后重新运行。

虽然在 customtkinter 中 time.sleep() 不起作用,而且我看到你可以在 tkinter 中使用“after”函数,但我无法让它与 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)
python-3.x customtkinter
1个回答
0
投票

time.sleep()
函数不适用于 customtkinter,因为它会冻结应用程序正在运行的线程。要解决此问题,您应该使用
after()
方法,正如您所看到的。此方法在给定时间后调用函数,并且不会冻结应用程序。

要使用此方法,您应该将

time.sleep(1)
行替换为
master.after(1000, auto_click)

您的完整代码现在是:

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)

(我还用

init()
替换了
__init__()
方法,因此您不必调用
init()
方法:您的类会自动调用
__init__()
方法)

希望我能帮到你,祝你有美好的一天

© www.soinside.com 2019 - 2024. All rights reserved.