Plug Fire
Plug Fire

Reputation: 127

Tkinter changing behavior based on inheritance

I know this looks like a lot of code but throw it into python and run it. You'll see the problem immediately, and you'll see that the code is mostly just a style sheet.

I have a black frame. Inside of that is a gray frame named "selections" that takes up 60% height and width. I want to put a bunch of buttons inside of the gray frame. These are custom buttons inherited from a customButton class I created.

However relx and rely are not functioning properly.

from tkinter import *

root = Tk()
root.resizable(width=FALSE, height=FALSE)
root.geometry("1024x768")
root.config(background="black")

# The base class
class customButton(Label):
    def __init__(self, *args, **kwargs):
        Label.__init__(self, *args, **kwargs)
        self.config(
            background="black",   #background of just the button
            foreground="white"    #font color
        )

#The child class
class travelButton(customButton):
    def __init__(self, *args, **kwargs):        #All of this garbage is required just to
        super().__init__()                      #change the text
        self.config(text="Travel")              #dynamically

def loadSelections():
    selectionWindow = Label(root)
    # Selection Window
    selectionWindow.config(
        background="gray",
        foreground="white"
    )

    selectionWindow.place(
        relwidth=0.6,
        relheight=0.6,
        relx=0,
        rely=0
    )

    #What I've tried but doesn't work
    travel = travelButton(selectionWindow)
    travel.config(
        background="red",
        foreground="white",
        text="Travel button. The gray should be 50%, but Tkinter is being weird about inheritance."
    )

    travel.place(
        relwidth=0.5,
        relheight=0.5,
        relx=0,
        rely=0
    )

    #De-comment this and comment out the "travel" stuff above to see what is supposed to happen
    """
    greenTester = Label(selectionWindow)
    greenTester.config(
        background="green",
        foreground="white",
        text="This works, but doesn't let me take advantage of inheritance."
    )

    greenTester.place(
        relwidth=0.5,
        relheight=0.5,
        relx=0,
        rely=0
    )
    """
loadSelections()

I need to create buttons dynamically, so inheritance would be a huge help.

Upvotes: 0

Views: 69

Answers (1)

furas
furas

Reputation: 142641

You forgot to use *args, **kwargs and travelButton doesn't inform Label who is its parent. Label doesn't know parent so it use root as parent.

You need

class travelButton(customButton):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

or

 class travelButton(customButton):
    def __init__(self, *args, **kwargs):
        customButton.__init__(self, *args, **kwargs)

Upvotes: 1

Related Questions