0

I want a checkbox that when check, creates a scrolled text widget and when unchecked, removes the widget.

Currently it creates the widget only once I've checked the box and then unchecked it, and then when checked again, it does nothing and when unchecked again, it creates a second widget below.

I've tried different ways of coding it but I can't figure out what I'm doing wrong.

# Creates Normal Checkbutton
chk_state = BooleanVar()
chk_state.set(False)  # set check state
chk = Checkbutton(window, text='Normal Entries', var=chk_state)
chk.place(x=0, y=0)

#Checks Checkbutton State
def chk_checked(event):
    txt = scrolledtext.ScrolledText(window, height=15, width=35)
    if chk_state.get():
        txt.insert(END, 'Paste Normal Entries Here...')
        txt.pack(anchor='nw', padx=50, pady=50)
    elif txt.winfo_exists():
        txt.pack_forget()
    else:
        pass

#Event when checkbox checked
chk.bind('<Button-1>', chk_checked)
1
  • What have you done to debug this? Have you verified your function is betting called? Have you verified that chk_state.get() is returning what you think it should? Have you verified that the correct conditional statement is being executed? Why are you creating a new widget every time the function is called, whether the button is checked or not? Commented Apr 11, 2019 at 13:49

1 Answer 1

2

You can try as this

import tkinter as tk
from tkinter.scrolledtext import ScrolledText

def chk_checked():
    global txt
    if chk_state.get():
        txt = ScrolledText(window, height=15, width=35)
        txt.insert(tk.END, 'Paste Normal Entries Here...')
        txt.pack(anchor='nw', padx=50, pady=50)
    else:
        txt.pack_forget()

window = tk.Tk()
chk_state = tk.BooleanVar()
chk_state.set(False)  # set check state
chk = tk.Checkbutton(window, text='Normal Entries', var=chk_state, command=chk_checked)
chk.place(x=0, y=0)
txt = None

window.mainloop()

This isn't the best way for do that, maybe you can create a class, i think that would be better.

The problem with your code is that each time that you click the CheckButton the function chk_checked(event) creates a new ScrolledText and after works on it instead working on the ScrolledText that was created previously. You have to declare a global variable (instead of a local variable) in wich you store the ScrolledText that you want to use and work only with it

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.