jeudi 30 septembre 2021

How does a Tkinter checkbox control corresponding textbox widget? Python

I have a simple tkinter program, where upon clicking a "Create boxes" button, it creates a Checkbutton and a Text widget. I was trying to enable/disable the Text widget based on the Checkbutton. eg- if the Checkbutton is ticked the corresponding Text button will be disabled.

And the following code does work as desired, but I have no idea how? How does a Checkbutton keep track of the corresponding Text widget?

I have tried it with multiple Checkbuttons and they all don't seem to interfere with the other's Text widgets.

from tkinter import *

root = Tk()
root.geometry('500x300')

def create_boxes():

    def disable_text():
        if textbox['state'] == NORMAL:
            textbox['state'] = DISABLED
        else:
            textbox['state'] = NORMAL


    checkbox = Checkbutton(root, command = disable_text)
    textbox = Text(root, height= 1, width = 30)

    checkbox.pack()
    textbox.pack()

create_chechkbutton = Button(root, text= 'Create a checkbox and textbox', command= create_boxes)
create_chechkbutton.pack()

root.mainloop()

Any explanation is appreciated.




Aucun commentaire:

Enregistrer un commentaire