1

I was "experimenting" new things with tkinter (i am a beginner with it) and i made, only for fun obviously, this application :

from tkinter import *

def text() :
    if checking :
        content.grid_forget()
    else :
        content = Label(root, text = txt.get()).grid(row = 3, column = 0) 

def check() :
    checking = True
    text()

root = Tk()

txt = StringVar()
checking = False

bt1 = Button(root, text = "Print me!", command = text)
bt2 = Button(root, text = "Clear!", command = check)
txt1 = Entry(root, textvariable = txt)

row = 0
for i in [bt1, bt2, txt1] :
    i.grid(row = row, column = 0)
    row+=1

root.mainloop()

My question is, why isn't the "clear" button working?

Alessandro Di Cicco
  • 147
  • 1
  • 2
  • 10

1 Answers1

1

There are several issues with your app, you might want to consider rethinking the structure and your widget management. please consider reading (http://effbot.org/tkinterbook/grid.htm) and check other posts on stackoverflow and make sure you check @Bryan Oakley past and present comments.

You are using local variables as he mentioned, this is easily corrected by declaring it as global as follows:

global variable_name

in your code,

additionally, you might want to consider restructuring your content ("label") when you add it to your root window: from:

content = Label(root, text = txt.get()).grid(row = 3, column = 0) 

to:

content = Label(root, text = txt.get())
content.grid(row = 3, column = 0) 

if you are not sure of what is going on , consider adding print() to your code, here is a quick snippet:

def text() :
    global content
    print(root.grid_slaves())
    if checking :
        content = Label(root, text = txt.get())
        content.grid(row = 3, column = 0)

you will immediately see that every time you click on print me, widgets are added to your layout.

best practices for your layout (Best way to structure a tkinter application)

Quick Hint:

def text() :
    print(checking)
    if checking :
        content.grid_forget()
    else :
        content = Label(root, text = txt.get()).grid(row = 3, column = 0) 

def check() :
    checking = True
    text()

root = Tk()

txt = StringVar()
checking = False

checking is always False... you might consider rethinking some logic as well

Community
  • 1
  • 1
glls
  • 2,325
  • 1
  • 22
  • 39