Tkinter link Intvar() with a function and button

Viewed 70

As the title suggests, I'm trying to make a counter with IntVar(),so I've tried this.

from tkinter import *

def main():
    root = Tk()
    root.resizable(FALSE, FALSE)
    root.geometry('200x50')
    root.title('Home')

    #starts here
    var = IntVar()
    text = 'Count: ' + str(var.get())

    b1 = Button(root, text='Test', command=fun)
    b1.pack()
    l1 = Label(root, text=text)
    l1.pack()

    mainloop()

def fun():
    for i in range(1, 11):
        print('test')

main()

But I got confused, I want to make it count the printings and show the value in the label.

Any help would be appreciated.

1 Answers

If you are trying to count the number of times 'test' is printed, you can update the l1 widget with l1['text'] = var after updating. To update, you can fetch the variable of intvar and then add 1 to it. Here's some code:

from tkinter import *

def main():
    root = Tk()
    root.resizable(FALSE, FALSE)
    root.geometry('200x50')
    root.title('Home')

    #starts here
    var = IntVar()
    text = 'Count: ' + str(var.get())

    b1 = Button(root, text='Test', command=lambda: fun(l1, var))
    b1.pack()
    l1 = Label(root, text=text)
    l1.pack()

    mainloop()

def fun(l1, var):
    for i in range(1, 11):
        print('test')
        var.set(var.get()+1)
        l1['text'] = 'Count: ' + str(var.get())

main()
Related