Python Forum

Full Version: OOP Label In Tkinter
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey! I AM Trying Use Label In Tkinter In OOP Way But I AM Trying To Pack Label I Don't Know How to?
Here Is Code:
from tkinter import *
from tkinter import ttk

def labels(master,self):
    var = StringVar()
    var.set(self)
    master.label = Label(master,text=var)
    master.pack()
if __name__ == "__main__":
    window = Tk()
    labels(window,"LOL")
    window.mainloop()
Here is The Error:
Error:
Traceback (most recent call last): File "c:\Users\DELL\Desktop\Download Manager In Tkinter\Main.py", line 11, in <module> labels(window,"LOL") File "c:\Users\DELL\Desktop\Download Manager In Tkinter\Main.py", line 8, in labels master.pack() File "C:\Users\DELL\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 2345, in __getattr__ return getattr(self.tk, attr) AttributeError: '_tkinter.tkapp' object has no attribute 'pack'
try
master.label.pack()
You want to pack the widget you created, not the parent. And generally you don't modify the parent object, you keep track of the widgets yourself (put them in a list or a dict or something). Also, using a variable called "self" when it's not referring to an object reference is non-standard. I'd rename that variable in your function.

I would try:

def labels(master,text):
    var = StringVar()
    var.set(text)
    mylabel = Label(master,text=var)
    mylabel.pack()