Home > Software design >  Python Tkinter widgets not showing when parent is self only root why?
Python Tkinter widgets not showing when parent is self only root why?

Time:06-15

I am making a GUI and this is the same exact code from another project were the widgets show up when self is their parent. But for some reason in this script they only will show if root is set as parent why? The Image Label does not show but the frame does and vice versa if I switch the parents.

import tkinter as tk
import PIL.Image
import PIL.ImageTk
import sys, os

#GUI Class
class MainGUI(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self,parent)
        self.parent=parent
        
        self.test()

    def test(self):
        self.bImage = PIL.ImageTk.PhotoImage(PIL.Image.open("Background.png"))
        self.bLabel = tk.Label(self, image=self.bImage)
        self.bLabel.image=self.bImage
        self.bLabel.place(x=0,y=0,width=300,height=400)

        self.test = tk.Frame(root, bg="red")
        self.test.place(x=10,y=10,width=50,height=50)
        

if __name__ == "__main__":
    root=tk.Tk()
    root.title("Buddy Swap")
    root.geometry("300x400")
    root.resizable(0,0)
    root.iconbitmap(os.path.dirname(sys.argv[0]) "\\Icon.ico")
    MainGUI(root).pack()
    root.mainloop()

CodePudding user response:

The problem is that you're using place for the label. place doesn't cause the containing widget to grow or shrink so the frame is staying its default size of 1x1 pixel.

Unless you are very careful with place these sorts of problems can happen quite easily, and this is one of the reasons I recommend either grid or pack over place in almost every circumstance.

A simple fix is to either give your MainGUI frame a size so that the widgets inside are visible, or stop using place.

  • Related