问题
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:
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)
来源:https://stackoverflow.com/questions/42317990/proper-use-of-inheritance-in-tkinter-using-button-widget