Here's an example with 3 buttons:
import tkinter as tk
import sys
class TryButtons(tk.Frame):
def __init__(self, title='Try Buttons', parent=None):
self.has_parent = False
if parent is None:
self.parent = tk.Tk()
else:
self.parent = parent
self.has_parent = True
self.parent.geometry('160x60+10+10')
tk.Frame.__init__(self, self.parent)
self.grid()
self.add_some_buttons()
def add_some_buttons(self):
self.button1 = tk.Button(self.parent, text='Left')
self.button2 = tk.Button(self.parent, text='Middle')
self.button3 = tk.Button(self.parent, text='Right')
self.quit = tk.Button(self.parent, text='QUIT')
self.button1.grid(row=0, column=0, padx=2, pady=2, sticky='nsew')
self.button2.grid(row=0, column=1, padx=2, pady=2, sticky='nsew')
self.button3.grid(row=0, column=2, padx=2, pady=2, sticky='nsew')
self.quit.grid(row=1, column=1, padx=2, pady=2, sticky='nsew')
self.button1.bind('<Button-1>', self.button_pressed)
self.button2.bind('<Button-1>', self.button_pressed)
self.button3.bind('<Button-1>', self.button_pressed)
self.quit.bind('<Button-1>', self.button_pressed)
if not self.has_parent:
self.mainloop()
def button_pressed(self, event):
text = event.widget.cget("text")
print(text)
if text == 'QUIT':
self.parent.destroy()
sys.exit()
def testit():
TryButtons(title='No parent')
if __name__ == '__main__':
testit()
the class can be instantiated with or without a parent.
In this example, (line 39) I instantiate without
- lines 6 - 11: Check to see if parent has been passed as argument
- if No: (line 8) create a root window as parent
- if yes: (lines 10, 11) use it and set flag which will be used to create mainloop if necessary
- Line 12 - Set window to be 160 x 60 pixels indented 10 on both x and y
- Line 13 - Initialize the tkinter Frame (inherited)
- Line 14 - Call grid to position Frame
- Line 16 - Add the buttons
- Lines 19-22 - create button widgets
- Lines 24-27 - Set button positions on Frame (self.parent)
- Lines 29-32 - Bind buttons to same method (you can use separate methods for each if you wish
- Lines 34-35 - add mainloop is parent created here.
- Lines 37-39 - Determine which button was pressed (event.widget) and print text value
- Lines 40-42 - Quit application if quit button pressed