Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 单击按钮后在同一gui中显示标签_Python_Tkinter - Fatal编程技术网

Python 单击按钮后在同一gui中显示标签

Python 单击按钮后在同一gui中显示标签,python,tkinter,Python,Tkinter,我试图制作一个程序,在同一个GUI中单击按钮后,在GUI中显示标签'HI' 我的代码: 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=Tru

我试图制作一个程序,在同一个GUI中单击按钮后,在GUI中显示标签
'HI'

我的代码:

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()
但我得到的错误是:

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

单击按钮后,请帮助我在同一GUI中显示标签
'HI'
'CLICK'

当前是
\uu init\uu
方法的本地标签。换句话说,无法从
\uuuu init\uuuu
外部访问它。这意味着当您在
retrieve\u inpu
中使用它时,Python将无法找到名称,因此将引发
namererror

只需将
txt\u frm
App
的实例属性设置为:

self.txt_frm = tki.Frame(self.root, width=900, height=900)
self.txt_frm.pack(fill="both", expand=True)
现在,可以通过
self
访问
txt\u frm
,这意味着您可以在
检索\u inpu
中使用它:

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

这是因为在创建按钮时也需要使用
self.txt\u frm
button3=tki.button(self.txt\u frm,…)
txt\u frm
现在是
App
的实例属性,因此必须始终通过
self
访问它。