Monday, June 15, 2015

tk4. Checkbutton in TKinter

Checkbuttons are similar to Buttons. Now the toggling action of checking or unchecking will be the status. Whenever the state changes, we invoke the function statusChanged. This function displays the current value of the checkbutton.


We again use a 2 by 2 grid, within a Frame, with the 3 widgets being a checkbutton, static label, and non-static Label (named display).


Now, we have 2 StringVar objects, one for the checkbutton and the other for the display Label.


There is no reason to have the statusChanged function be a separate function, since it is only 1-line. We can also put it, inline, as a lambda function.

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

def statusChanged():
    display.set(status.get())
    
root=Tk()
root.title('Checkbutton Status')
root.geometry('300x100')
frame = Frame(root)
frame.pack()
status = StringVar()
checkbutton = Checkbutton(frame, text='status\ncheckbutton', 
     command=statusChanged, variable=status,
     onvalue='on', offvalue='off')
checkbutton.grid(row = 1, column= 0)
label = Label(frame, text = 'status', pad = 5)
label.grid(row = 0, column = 1)
display = StringVar()
display.set('off')
label1 = Label(frame, textvariable = display, pad = 5)
label1.grid(row = 1, column = 1)
root.mainloop()

Output:

No comments:

Post a Comment