Python Tkinter one callback function for two buttons -
i have been looking around long time answers question still hasn't find anything. creating gui using tkinter, , have 2 buttons same thing except receive information different widgets. 1 button entry widget , other listbox widget. callback function these 2 buttons long (about 200 lines), don't want have separate functions each button. have if-statements in beginning of callback function check button clicked, , codes take corresponding value. not sure if following code shows right way because apparently doesn't work in program. callback function work first time, , if click other button receive error. here sample code created illustrate idea. note want check if button clicked, not want check if 'value' exists. please help.
from tkinter import * root = tk() def dosomething(): # right way check button clicked? if button1: value = user_input.get() elif button2: value = choice.get(choice.curselection()[0]) # more codes take 'value' input. button1 = button(master,text='search',command=dosomething) button1.pack() button2 = button(master,text='search',command=dosomething) button2.pack() user_input = entry(master) user_input.pack() choice = listbox(master,selectmode=single) choice.pack() #assume there items in listbox, skipped portion root.mainloop()
if want pass actual widget callback, can this:
button1 = button(master, text='search') button1.configure(command=lambda widget=button1: dosomething(widget)) button2 = button(master, text='search') button2.configure(command=lambda widget=button2: dosomething(widget))
another choice pass in literal string if don't need reference widget:
button1 = button(..., command=lambda widget="button1": dosomething(widget)) button2 = button(..., command=lambda widget="button2": dosomething(widget))
another choice give each button unique callback, , have callback thing unique button:
button1 = button(..., command=buttononecallback) button2 = button(..., command=buttontwocallback) def buttononecallback(): value = user_input.get() dosomething(value) def buttontwocallback(): value=choice.get(choice.curselection()[0]) dosomething(value) def dosomething(value): ...
there other ways solve same problem, give general idea of how pass values button callback, or how can avoid needing in first place.
Comments
Post a Comment