SleepyViking
SleepyViking

Reputation: 59

Working with a GUI without using OOP

from tkinter import *
root = Tk()
root.title("Button Counter without OOP")
root.geometry("200x85")
app = Frame(root)
app.grid()
bttn = Button(app)
bttn["text"] = "Total Clicks: 0"
bttn.grid()
bttn_clicks = 0
while True:
    if bttn:
        bttn_clicks += 1
        bttn["text"] = "Total Clicks: " + str(bttn_clicks)
        bttn.grid()

I can't seem to get this to work. I want the button to count the clicks without using OOP to make this happen.

Upvotes: 0

Views: 312

Answers (1)

falsetru
falsetru

Reputation: 369074

You need to define a callback function that will called when button is clicked, and bind it using command option of the Button object.

from tkinter import *

bttn_clicks = 0
def on_button_click():
    global bttn_clicks
    bttn_clicks += 1
    bttn["text"] = "Total Clicks: " + str(bttn_clicks)

root = Tk()
root.title("Button Counter without OOP")
root.geometry("200x85")
app = Frame(root)
app.grid()
bttn = Button(app, command=on_button_click)  # <---------
bttn["text"] = "Total Clicks: 0"
bttn.grid()
root.mainloop()

Upvotes: 3

Related Questions