Tkinter语言 - 我可以在不受干扰的情况下使用多个 after 函数吗?



我正在尝试使用python制作一个答题器游戏。我正在使用 tkinter 作为 GUI。我正在尝试在函数中使用 .after 函数将整数添加到总数中。我已经设置了它,所以它每秒增加 1 个,效果很好。我正在尝试使用每秒增加 5,10,15 的多个函数来做到这一点。after函数工作正常,直到一次有多个函数。一旦有多个时间,时间就会加速,一旦它们开始加起来,它就会每几分之一秒增加一次。

这是我代码的简化版本:

import tkinter as tk
window = tk.Tk()
window.geometry("800x700")  #makes the window size 900x700
window.resizable(0, 0)  #make it so window cannot be resized
total = 0
def addone():
    global total
    total = total + 1
    add = window.after(1000, addone)
    print(total)
button = tk.Button(command=addone, width=10, height=10)
button.grid(column=1, row=1)
window.mainloop()

每次点击按钮时,总数加起来越来越快。我似乎找不到一种方法让它停止这种情况。我正在尝试让它每秒增加 1 次,然后在单击按钮后每秒添加 2 次,依此类推。

如果我

理解你的问题,试试这样:

这将使当您单击按钮时,它将添加 1,下次它将添加 1+1,下次它将添加 1+2 等:

import tkinter as tk
window = tk.Tk()
window.geometry("800x700")  #makes the window size 900x700
window.resizable(0, 0)  #make it so window cannot be resized
total = 0
number = 1
def addone():
    global total
    total = total + number
    number = number + 1
    add = window.after(1000, addone)
    print(total)
button = tk.Button(command=addone, width=10, height=10)
button.grid(column=1, row=1)
window.mainloop()

如果您希望它相乘而不是添加,请执行以下操作:

import thinker as to
window = tk.Tk()
window.geometry("800x700")  #makes the window size 900x700
window.resizable(0, 0)  #make it so window cannot be resized
total = 0
number = 1
def addone():
    global total
    total = total + number
    number = number * 1
    add = window.after(1000, addone)
    print(total)
button = tk.Button(command=addone, width=10, height=10)
button.grid(column=1, row=1)
window.mainloop()

对不起,如果那想要你的意思,但如果你能更好地解释它,它会有很大帮助!

最新更新