如何使StringVariable中的数字在Tkinter中每5秒增加1



所以我一直在Tkinter中编写Cookie Clicker原型,我遇到了这个问题:

我首先做了一个选项,当按下时,每次点击都值2分(它有价格(。

然后我想做另一个选项,当按下时,每5秒加1分但我还没有找到让它发挥作用的方法(我还没有设定价格,因为它还不起作用(。

from tkinter import *
import time
#funciones y variables
clicks = 0
incrementer = 1
price1 = 1
loop1 = 0

def sumar():
global clicks
clicks += incrementer
you.set("Has dado " +str(clicks)+ " clicks")
def shop1():
global clicks
global incrementer
if clicks < price1:
return
elif clicks >= price1:
clicks -= price1
incrementer = 2
you.set("Has dado " +str(clicks)+ " clicks")
buy1.destroy()
buy2.place(x=52, y=155)
def shop2():
global loop1
loop1 = int(1)
buy2.destroy()
while loop1 == 1:
interface.update()
time.sleep(5)
clicks += 1
you.set("Has dado " + str(clicks) + " clicks")

#Ventana y su configuración
interface = Tk()
interface.title("Cokie Test")
interface.geometry("200x200")
interface.resizable(False, False)
interface.configure(bg="black")
#Botón y changeable value
buy2 = Button(interface, bg="black", fg="white", text="Comprar Auto 1", command=shop2)
buy1 = Button(interface, bg="black", fg="white", text="Comprar x2", command=shop1)
buy1.place(x=62, y=155)
clickerimg = PhotoImage(file="C:/Users/Eduardo/OneDrive/Escritorio/Programming/botoncito.png")
clicker = Button(interface, command=sumar)
clicker.config(image=clickerimg)
clicker.pack(pady=20)
you = StringVar()
you.set("Has dado 0 clicks")
clickss = Label(interface, bg="black",fg="white", textvariable=you)
clickss.place(x=49,y=123)

interface.mainloop()

所以我尝试了这个,期望它每5秒加1分

def shop2():
global loop1
loop1 = int(1)
buy2.destroy()
while loop1 == 1:
interface.update()
time.sleep(5)
clicks += 1
you.set("Has dado " + str(clicks) + " clicks")

但它没有回应

Tkinter小部件有一个名为after的方法,可用于调度将来运行的函数。如果该函数本身调用after来重新调度自己,那么它将在应用程序的整个生命周期内继续运行。

after的第一个参数是以毫秒为单位的延迟。第二个参数是对函数的引用。任何附加参数都将作为位置参数传递给该函数。

这里有一个非常简单的例子:

import tkinter as tk
def tick():
value = points.get()
points.set(value+1)
root.after(5000, tick)

root = tk.Tk()
points = tk.IntVar(root, value=0)
label = tk.Label(root, textvariable=points)
label.pack(padx=20, pady=20)
tick()
root.mainloop()

最新更新