在 tkinter 中的函数内调用函数 [英] call a function inside a function in tkinter

查看:29
本文介绍了在 tkinter 中的函数内调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从按钮调用 rest 函数时,然后 start 函数被调用并每秒继续打印值但是当我再次调用 rest 函数时start 函数再次调用,但这次 start 函数以 2 倍速度打印值,依此类推.

when calling rest function from button, then start function is called and prints values continues every second But when I call again rest function the start function call again but this time start function print values in 2x speed and so on.

但我不想以 2 倍的速度打印值.我正在做一个小项目,我面临这种类型的问题,所以这就是我编写这个小代码的原因.请解决我的问题

But I don't want to print value in 2x speed. I am making a small project where I face this type of problem so that is why I write this small code. Please solve my problem

import tkinter as tk

window = tk.Tk()
window.geometry('400x400')

i = 0

def start():
    global i
    text_label .config(text=i)
    i += 1
    text_label .after(1000, start)

def rest():
    global i
    i=0
    start()

text_label = tk.Label(window, text="start")
text_label .pack()

tk.Button(window, text="rest", command=rest).pack()

window.mainloop()

推荐答案

发生的事情是,每次调用 reset 时,都会启动一个新的 callback,它将调用start 无限期每 100 毫秒.每个回调都是独立的,并且不知道其他回调,这会导致一系列回调,每个回调在自己的时间调用 start,每 100 毫秒.

What is happening is that every time you call reset, a new callback is launched that will call start indefinitely every 100ms. Every callback being independent, and having no knowledge of the others, this results in a series of callbacks each calling start on their own time, every 100 ms.

为了避免这种滚雪球",您需要取消之前的回调才能正确重置.您可以通过保持对 callback 的引用,并在 reset 中调用 tk.after_cancel(callback_id) 来做到这一点.

To avoid this "snowballing", you need to cancel the previous callbacks in order to reset properly. You do this by keeping a reference on the callback, and calling tk.after_cancel(callback_id) in reset.

像这样:

import tkinter as tk


def start():
    global i, callback_id
    text_label.config(text=i)
    i += 1
    callback_id = text_label.after(1000, start)


def reset():
    global i, callback_id
    i = 0
    if callback_id is not None:
        text_label.after_cancel(callback_id)
        callback_id = None
    start()


window = tk.Tk()
window.geometry('400x400')

text_label = tk.Label(window, text="start")
text_label.pack()

callback_id, i = None, 0
tk.Button(window, text="reset", command=reset).pack()

window.mainloop()

这篇关于在 tkinter 中的函数内调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆