0

I wanted to have a text inserted in a textbox that is in a toplevel window, but I wanted it to depend on a checkbox if it is ticked or not. For example, if the checkbox is ticked, the textbox will show apple if not it should show orange. I added print in the check_checkbox function to see if something is wrong with it, it seems that it is working but I cant make it appear in the textbox.

from tkinter import ttk
import tkinter.scrolledtext as st

root = tk.Tk()

root.geometry("100x100")
root.title("Test")



def check_checkbox():
    if isChecked.get() == 1:
        testVar = tk.StringVar(root, "apple")
    else:
        testVar = tk.StringVar(root, "orange")
    print(testVar.get())

def new_win(testVar):
    win = tk.Toplevel(root)
    win.geometry("100x100")
    win.title("Test 2")
    
    win_txt_box = st.ScrolledText(win, height=50, width=50)
    win_txt_box.pack()

    win_txt_box.insert("1.0", f""+testVar+"")
    return;


testVar = tk.StringVar()
isChecked = tk.IntVar()

# checkbox
check_box = ttk.Checkbutton(root, text="CHECK THIS",
                                  command=check_checkbox,
                                  variable=isChecked,
                                  onvalue=1,
                                  offvalue=0,)
check_box.grid(column=0, row=0)

# button
test_button = ttk.Button(root, text="CLICK THIS", command=lambda: new_win(testVar.get()))
test_button.grid(column=0, row=1)


root.mainloop()```
0

1 Answer 1

1

Add a global inside function. There are only three changes in line 13, 18 and 28. 

def check_checkbox():
    global x
    if isChecked.get() == 1:
        testVar = tk.StringVar(root, "apple")
    else:
        testVar = tk.StringVar(root, "orange")
    x = (testVar.get())

def new_win(testVar):
    win = tk.Toplevel(root)
    win.geometry("100x100")
    win.title("Test 2")
    
    win_txt_box = st.ScrolledText(win, height=50, width=50)
    win_txt_box.pack()

    win_txt_box.insert("1.0", x)
    return

Result:

enter image description here]

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.