1

This concerns Python and Tkinter.

  1. I wish to have a Label widget display the word "Meow".

  2. The Label widget should be the child of a Frame in a Tk window.

This seems simple, yet the code below does not work - nothing appears:

import tkinter as tk

class Options(tk.Frame):

    def __init__(self, gui_parent):

        super().__init__()
        tk.Label(self, text="Meow").pack()

class Gui(tk.Tk):

    def __init__(self):

        super().__init__()
        Options(self)

gui = Gui()
gui.mainloop()

I then experimented: if I change the Label widget to tk.Label(gui_parent, text="Meow").pack(), the content of the window then appears. (However this is not the 'correct' behaviour, since I wish for the Label widget to be a direct child of the Frame widget, not of the Tk parent window.)

To my understanding, super().__init__() should have instantiated a Frame. The Label widget should then be able to access the Frame via self. This is not so.

Where have I gone wrong?

xax
  • 2,043
  • 4
  • 24
  • 28

1 Answers1

2

You do not pack your Options widget. Try with:

Options(self).pack()

Also, I would explicitly state that Options is the child of Gui, so you should pass gui_parent to the __init__ function of Options objects:

def __init__(self, gui_parent):
    super().__init__(gui_parent)
    tk.Label(self, text="Meow").pack()
Pier Paolo
  • 878
  • 1
  • 14
  • 23
  • Thank you! I did not know that had to be packed, or the gui_parent in `init`. One further question: how do I modify the instantiated Frame's background colour? I tried changing it to `super().__init__(background='red')` and `super().__init__(bg='red')`, and I even tried `self.config(background='red')` but none of them work. The idea is to have "Meow" on a red background. – xax Jun 06 '17 at 16:27
  • 1
    @anonnoir: Sorry, I don't really know. Try to look at the following questions: https://stackoverflow.com/questions/11413459/adding-label-to-frame-in-tkinter-ignores-the-attributes-of-frame, https://stackoverflow.com/questions/27633545/tkinter-frame-background-disappear-when-i-associate-a-label-to-it, https://stackoverflow.com/questions/16639125/how-do-i-change-the-background-of-a-frame-in-tkinter. – Pier Paolo Jun 06 '17 at 17:09
  • 1
    I improvised off the answers for some of those questions, particularly this one -- https://stackoverflow.com/a/11414185/283169. It then worked. Thank you for the guidance! – xax Jun 07 '17 at 11:02