问题
I'm trying to pass an argument to a button click func and encountering an issues.
In short, I am trying to get a button press to pop up out the askColor()
method, and return that colour value as the background colour of the related textbox.
Its function is so synaesthets can associate a colour with a letter/number and record the resulting colour list.
specific lines:
self.boxA = Text(self.mainframe, state='normal', width=3, height=1, wrap='word', background=self.AVal).grid(column=2, row=2, padx=4)
self.boxB = Text(self.mainframe, state='normal', width=3, height=1, wrap='word', background=self.AVal).grid(column=3, row=2, padx=4)
self.boxC = Text(self.mainframe, state='normal', width=3, height=1, wrap='word', background=self.AVal).grid(column=4, row=2, padx=4)
self.ABlob = ttk.Button(self.mainframe, text="A",style= 'mainSmall.TButton', command= lambda: self.getColour(self.boxA)).grid(column=2, row=3)
self.BBlob = ttk.Button(self.mainframe, text="B",style= 'mainSmall.TButton', command= lambda: self.getColour(self.boxB)).grid(column=3, row=3)
self.CBlob = ttk.Button(self.mainframe, text="C",style= 'mainSmall.TButton', command= lambda: self.getColour(self.boxC)).grid(column=4, row=3)
and:
def getColour(self,glyphRef):
(triple, hexstr) = askcolor()
if hexstr:
glyphRef.config(bg=hexstr)
The problem is that I can't seem to reference self.ABlob
in the way I am trying - it returns type None
. I have tried including a pack.forget
command in the button click func, but that also doesn't work.
回答1:
The main part of your question seems to be:
The problem is that I can't seem to reference self.ABlob in the way I am trying - it returns type None
When you do x=ClassA(...).func(...)
, x contains the result of the call to func
. Thus, when you do self.ABlob = ttk.Button(...).grid(...)
, what is stored in self.ABlob
is None
, because that is what is returned by the grid function.
If you want to store a reference to the button you will need to create the button and then call grid as two separate steps:
self.ABlob = ttk.Button(...)
self.ABlob.grid(...)
Personally I see this as a best practice, especially when you're using grid. By putting all of your grid statements in a block it becomes easier to visualize the layout and spot bugs:
self.ABlob.grid(row=3, column=2)
self.BBlob.grid(row=3, column=3)
self.CBlob.grid(row=3, column=4)
来源:https://stackoverflow.com/questions/14301078/python-ttk-tkinter-passing-an-argument-with-a-button-click-func