Just to be clear, if the goal is just to print whatever text the button is showing, the simplest is to just have separate command
functions, as you have done. It's then explicitly clear which button was there at the time of the click. So by this I mean, just add a print
statement in the stop
function.
But assuming there is a more nuanced situation where you actually need to determine what is packed in a different part of the program, this is an example based on what @acw1668 suggested in the comments:
from tkinter import *
packed = 'B1'
def start():
global packed
B1.pack_forget()
B2.pack()
packed = 'B2'
def stop():
global packed
B2.pack_forget()
B1.pack()
packed = 'B1'
def check():
if packed == 'B1':
print("Start")
elif packed == 'B2':
print("Stop")
root = Tk()
root.title("TestWin")
B1 = Button(root, text='start', command=start)
B1.pack(side=TOP)
B2 = Button(root, text='stop', command=stop)
B3 = Button(root, text='check', command=check)
B3.pack(side=BOTTOM)
root.mainloop()
The new button ("check") determines what button is packed, based on the flag packed
(just to note, if you instead wrap the application in class
(see here), you could avoid having to use global
).
The above is more than sufficient, but if you actually want to check the button object itself, you can check the packed elements in a Frame with pack_slaves()
:
from tkinter import *
def start():
B1.pack_forget()
B2.pack()
def stop():
B2.pack_forget()
B1.pack()
def check():
global button_frame
button = button_frame.pack_slaves()[0]
text = (button.cget('text'))
if text == 'start':
print('Start')
elif text == 'stop':
print('Stop')
root = Tk()
root.title("TestWin")
button_frame = Frame(root,)
button_frame.pack(side=TOP)
B1 = Button(button_frame, text='start', command=start)
B1.pack()
B2 = Button(button_frame, text='stop', command=stop)
B3 = Button(root, text='check', command=check)
B3.pack(side=BOTTOM)
root.mainloop()
This second example sounds more similar to the logic you described; i.e. find object corresponding to the pressed button, then get its text using cget
, and route that to determine what is printed. Note that this example finds the button widget by using button = button_frame.pack_slaves()[0]
, so there is an assumption that there will only be clearly one button packed in button_frame
.
Another option would be to use bind
to program the button's effects, rather than the command
parameter. You could then create a function like check
in the above example to bind to both buttons, and you could use this technique to get the pressed widget (and then check it's identity/text, determine what to print, etc....).