adsa lila
adsa lila

Reputation: 115

Displaying label in same gui after button is clicked

I am trying to make a program to display a label 'HI' within the GUI, only after clicking the button 'CLICK' within the same GUI.

My code:

import Tkinter as tki
class App(object):
     def __init__(self,root):
         self.root = root

         txt_frm = tki.Frame(self.root, width=900, height=900)
         txt_frm.pack(fill="both", expand=True)
         button3 = tki.Button(txt_frm,text="CLICK", command = self.retrieve_inpu)
         button3.grid(column=0,row=2)


     def retrieve_inpu(self):

        label = tki.Label(txt_frm,text='HI')
        label.grid(column=0,row=3)
root = tki.Tk()
app = App(root)
root.mainloop()

But I get error as:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "C:/Python27/teste.py", line 14, in retrieve_inpu
    label = tki.Label(txt_frm,text='HI')
NameError: global name 'txt_frm' is not defined

Please help me to display the label 'HI' in the same GUI after clicking the button 'CLICK'.

Upvotes: 1

Views: 450

Answers (1)

user2555451
user2555451

Reputation:

txt_frm is currently local to the __init__ method. In other words, there is no way to access it from outside of __init__. This means that when you use it inside retrieve_inpu, Python will be unable to find the name and will therefore raise a NameError.

You can fix this problem by simply making txt_frm and instance attribute of App:

self.txt_frm = tki.Frame(self.root, width=900, height=900)
self.txt_frm.pack(fill="both", expand=True)

Now, txt_frm is accessible through self, which means you can use it inside retrieve_inpu:

label = tki.Label(self.txt_frm,text='HI')

Upvotes: 2

Related Questions