2

I am writing a GUI in Tkinter using Python 2.11 using an OOP approach and trying to learn inheritance. I wrote a child class called ButtonField which is inherited from tk.Button. Inside ButtonField I have a method called pressMe which changes the color and text of the button when pressed.

My eventual goal is to have more buttons in the GUI and all the associated methods contained in the ButtonField class for cleaner and more manageable code.

When I press the Button the text "In Press Me Method" is displayed on the screen so the method is perhaps working but the button widget does not change text or background color.

import Tkinter as tk

class MainWindow(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.olFrame = tk.LabelFrame(text = 'Initial Frame', bg = 'grey')
        self.olFrame.grid(column = 0, row = 0, sticky = 'w')

        self.simpleButton = ButtonField(self.olFrame, text = "Press Me",bg= "green"
                                     ,command = ButtonField(self).pressMe)
        self.simpleButton.grid(column = 0, row = 0)

class ButtonField(tk.Button):
    def __init__(self, parent, *args, **kwargs):
        tk.Button.__init__(self, parent, *args, **kwargs)
        self.parent = parent

    def pressMe(self):
        print "In Press Me Method"
        self.configure(text = "Pressed Now", background = "yellow")
        #self.parent.configure(self, text = "Pressed Now", background = "yellow")  #returns TclError: unknow option "-text"

root = tk.Tk()
root.geometry('500x400')
root.title('Test GUI')
root.configure(background = "black")

a = MainWindow(root)
root.mainloop()
1
  • You have a good answer to the specific bug, your plan to use inheritance for everything, though, is not a good idea and will make your code more convoluted than it already is. Unless you're making entirely new widgets, just use composition and delegation as you'll see in most tkinter examples. Commented Feb 18, 2017 at 17:37

1 Answer 1

1

Consider this line of code:

self.simpleButton = ButtonField(..., command = ButtonField(self).pressMe)

It is exactly the same as if you did this:

another_button = Button(self)
self.simpleButton = ButtonField(..., command=another_button.pressMe)

Because you are calling the function of a different button which is invisible, you don't see the changes. If you want the button to call its own function you will need to do it in two steps:

self.simpleButton = ButtonField(...)
self.simpleButton.configure(command=self.simpleButton.pressMe)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.