1

In this program, I tried to create a loop that would increase the value of the variable X during each iteration

from tkinter import *

def func(x=0):
    x +=1
    root.after(10, func, x)
    print(x)
           
root = Tk()
btn1 = Button(root, text="click", command=func)
btn1.grid()
root.mainloop()

When I press the button for the first time everything works correctly. But when I press the button again, I see something like this:

    1
    2
    3
    4
    5
    6
    7
    1
    8
    2
    9
    3 
    10
    4 
    11
    5 
    12
    6 
    13
    7 
    14
    8
    15

It looks like the old and new values of the variable are mixed. I think I should remove the first func()run from mainloop() to do list. But how?

Mark
  • 13
  • 2

2 Answers2

0

You have to cancel the first loop, before starting a new loop:

import tkinter as tk

class Counter:
    def __init__(self, root):
        self.x = 0
        self.root = root
        self.id = None

    def restart(self):
        if self.id is not None:
            self.root.after_cancel(self.id)
        self.x = 0
        self.next()

    def next(self):
        self.x += 1
        print(self.x)
        self.id = self.root.after(10, self.next)

def main():
    root = tk.Tk()
    counter = Counter(root)
    tk.Button(root, text="click", command=counter.restart).pack()
    root.mainloop()

if __name__ == '__main__':
    main()
Daniel
  • 42,087
  • 4
  • 55
  • 81
0

Try this:

from tkinter import *

x = 0

def func():
    global x
    x += 1
    print(x)

root = Tk()
btn1 = Button(root, text="click", command=func)
btn1.grid()
root.mainloop()

or if you want to destroy it in 10 milliseconds:

from tkinter import *

x = 0

def func():
    global x
    x += 1
    print(x)
    root.after(10, root.destroy)

root = Tk()
btn1 = Button(root, text="click", command=func)
btn1.grid()
root.mainloop()

or to continously increase x

from tkinter import *

x = 0

def func():
    global x
    x += 1
    print(x)
    root.after(10, func)

root = Tk()
btn1 = Button(root, text="click", command=func)
btn1.grid()
root.mainloop()
m.i.cosacak
  • 708
  • 7
  • 21