Following Bryan Oakley's answer to this post Best way to structure a tkinter application?, I would like to move the contents of tab1 to its own class, but leave say_hello and get_item in the main class as they are. How do I do that?
import tkinter as tk
from tkinter import ttk, N, S, END, EXTENDED
class MainApplication(tk.Frame):
def __init__(self, root, *args, **kwargs):
tk.Frame.__init__(self, root, *args, **kwargs)
self.root = root
self.nb = ttk.Notebook(root)
self.tab1 = ttk.Frame(self.nb)
self.tab2 = ttk.Frame(self.nb)
self.nb.add(self.tab1, text='TAB1')
self.nb.add(self.tab2, text='TAB2')
self.nb.grid(row=0, column=0)
#contents of tab1 - which I would like to place in their own class
self.frame = tk.Frame(self.tab1)
self.frame.grid(row=0, column=0)
self.button = tk.Button(self.frame, text='Hello', command=self.say_hello)
self.button.grid(row=0, column=0)
self.items = ['A','B','C']
self.listbox = tk.Listbox(self.frame, selectmode=EXTENDED, exportselection=0)
self.listbox.grid(row=1, column=0)
self.scrollbar = tk.Scrollbar(self.frame, orient='vertical')
self.scrollbar.grid(row=1, column=1, sticky=N+S)
self.listbox.config(yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.listbox.yview)
self.listbox.bind('<<ListboxSelect>>', self.get_item)
for item in self.items:
self.listbox.insert(END, item)
#contents of tab2 - which should be in their own class
#...
#...
def say_hello(self):
print('hello')
def get_item(self, evt):
w = evt.widget
index = int(w.curselection()[0])
print('item selected = {}'.format(self.items[index]))
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root)
root.mainloop()
EDIT:
Thank you Saad for your detailed response. I ran your code, studied it, and learned quite a bit. However, I modified my question to make it more focused.