Sunday, June 14, 2015

tk3. Button and StringVar in Tkinter

The themed widgets from Tkinter will be used from now on, so the additional import in the code below.


The function increment, defined in the code, adds 1 to value currently held in a label.


Here, there are 3 widgets in total, within the Frame widget.


The 3 widgets take 3 of the 4 positions in a 2 by 2 grid. The button widget has text '+' and pressing it will invoke the increment function.


There are 2 labels. The first has the name label and is static with text of 'Counter'. The second, label1, can have the text updated using a StringVar object. We initialize it as '0' and update via the increment function.

# tk3.py
from tkinter import *
from tkinter.ttk import *

def increment():
    a = int(counter.get())
    counter.set(a+1)
    
root=Tk()
root.title('Button Counter')
root.geometry('200x100')
frame = Frame(root)
frame.pack()
button = Button(frame, text='+',
                    command = increment, pad = 5)
button.grid(row = 1, column= 0)
label = Label(frame, text = 'Counter', pad = 5)
label.grid(row = 0, column = 1)
counter = StringVar()
counter.set(0)
label1 = Label(frame, textvariable = counter, pad = 5)
label1.grid(row = 1, column = 1)
root.mainloop()

Output:

No comments:

Post a Comment