Home > OS >  Calling functions using a variable with self
Calling functions using a variable with self

Time:10-17

I have some code for an autocomplete combobox that I copied from the internet and I'm modifying it so I can change its properties like width, height, bindings, etc. through keywords like a normal combobox. I'm not sure how to go about calling the functions for the properties though because I need self. behind it to initiate the function. Here's a snippet of what I have:

from tkinter import *
from tkinter import ttk

class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.CBBox = AutoCompleteBox(self, height=3)
        self.CBBox.pack()

class AutoCompleteBox(ttk.Combobox):
    def __init__(self, parent, **kwargs):
        ttk.Combobox.__init__(self, parent)

        for key, value in kwargs.items():
            key(value)

    def height(self, height):
        self.config(height=height)

    def width(self, width):
        self.config(width=width)

my_app = App()
my_app.mainloop()

CodePudding user response:

If you're asking about how to pass kwargs to the base class, just pass them when you call __init__:

class AutoCompleteBox(ttk.Combobox):
    def __init__(self, parent, **kwargs):
        ttk.Combobox.__init__(self, parent, **kwargs)

To call a method on the base class, use super. Or, do like you do in the __init__ and invoke the class. super is preferred.

For example, if you wanted to call the configure method of the base class you could do something like this:

def width(self, width):
    super().config(width=width)

In this case it's not necessary, since self.config(...) will automatically call the config method on the base class since you haven't overridden that method in your class.

If you defined your own config method to do something else in addition to the default behavior, it might look something like this:

def config(self, **kwargs):
    print("config called:", kwargs)
    super().config(**kwargs)

Notice that if you remove the last line, when you call config it will print the message but it won't actually configure the widget.

  • Related