在条目小部件Tkinter旁边添加标签

时间:2015-04-11 21:34:23

标签: python tkinter widget label

我正在尝试在我的Tkinter GUI中的每个条目小部件旁边添加一个标签,但是这样做时,我收到一条错误global name Label not defined

到目前为止,这是我的代码:

import Tkinter as Tk

class SampleApp(Tk.Tk):

    def __init__(self):
        Tk.Tk.__init__(self)
        self.can_fname = Tk.Entry(self)
        self.can_lname = Tk.Entry(self)
        self.cl_fname = Tk.Entry(self)
        self.cl_lname = Tk.Entry(self)
        self.button = Tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.can_fname.pack()
        self.can_lname.pack()
        self.cl_fname.pack()
        self.cl_lname.pack()

    def on_button(self):
       a=self.can_fname.get()
       b='hello %s' %(a)
       with open('filename.txt', 'w') as myfile:
          myfile.write(b)

app = SampleApp()
app.mainloop()

1 个答案:

答案 0 :(得分:0)

只需使用网格管理器即可。使用以下代码:

import Tkinter as Tk

class SampleApp(Tk.Tk):
    def __init__(self):
        Tk.Tk.__init__(self)
        self.label = Tk.Label(self, text="My Label")
        self.entry = Tk.Entry(self)
        self.label.pack()
        self.entry.pack()
        self.label.grid(row=0, column=0, sticky=W)
        self.entry.grid(row=0, column=1, sticky=W)

app = SampleApp()
app.mainloop()