Nicolas T.
Nicolas T.

Reputation: 1

Newbie: How to implement a simple counter in a window

I'm a beginner in Python and I'm trying to implement a very simple program in Python3/Tk : a simple windows with one text sentence "You have clicked i times." and a button. When ones clicks on the button, the sentence updates the value of i to the next integer. Here's my code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tkinter import *
# Définition du compteur d'affichage
i=0
def f():
    global i
    i=i+1
# Corps du programme
def affichage():
    monTexte.set("Le nombre de clicks est "+str(i)+".")
# Affichage du texte 1
fen=Tk()
monTexte=StringVar()
monTexte.set("Le nombre de clicks est "+str(i)+".")
texteLabel = Label(fen, textvariable = monTexte)
texteLabel.pack()
# Affichage du bouton 1
btn=Button(fen, f(), text="+1", command=affichage)
btn.pack()
fen.mainloop()

I do understand that you have to execute the function f() every time one clicks on the button but the way I've implemented it executes the function only once. Maybe there's some kind of loop to implement but I don't know how to do it.

Thanks in advance,

Nicolas

Upvotes: 0

Views: 68

Answers (1)

Adam
Adam

Reputation: 131

You need to set the command that your button executes to the command that increments your i value eg:

btn=Button(fen, text="+1", command=f)

Where your function 'f' is:

def f():
    global i
    i=i+1
    monTexte.set("Le nombre de clicks est "+str(i)+".")

Program:

from tkinter import *

i=0
def f():
    global i
    i=i+1
    monTexte.set("Le nombre de clicks est "+str(i)+".")

fen=Tk()

monTexte=StringVar()
monTexte.set("Le nombre de clicks est "+str(i)+".")

texteLabel = Label(fen, textvariable = monTexte)
texteLabel.pack()

btn=Button(fen, text="+1", command=f)
btn.pack()

fen.mainloop()

Upvotes: 1

Related Questions