- Tkinter を利用して GUI アプリを作る際に,tab を利用する.
- オブジェクト指向で書く.
実行結果
tab1
tab2
say hello ボタンを押すと以下が表示される.
Hello World at tab2
コード
#!venv/bin/python
# -*- coding: utf8 -*-
import tkinter as tk
import tkinter.ttk as ttk
class Application(ttk.Notebook):
def __init__(self, master=None):
super().__init__(master)
self.master.title('window')
tab1 = tk.Frame(self.master)
self.add(tab1, text="tab1")
Tab1(master=tab1)
tab2 = tk.Frame(self.master)
self.add(tab2, text="tab2")
Tab2(master=tab2)
self._quit_outside_widget()
self.pack()
def _quit_outside_widget(self):
quit = tk.Button(self.master,
text="QUIT at outside",
command=root.destroy)
quit.pack(side=tk.BOTTOM)
class Tab1(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self._label_tab1_widget()
self._quit_tab1_widget()
self.pack()
def _label_tab1_widget(self):
label = tk.Label(self, text='Hello World at tab1')
label.pack()
def _quit_tab1_widget(self):
quit = tk.Button(self,
text="QUIT at tab1",
command=root.destroy)
quit.pack(side=tk.BOTTOM)
class Tab2(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self._start_tab2_widget()
self._quit_tab2_widget()
self.pack()
def _start_tab2_widget(self):
start_button = tk.Button(self,
text="say hello",
command=self._hello)
start_button.pack()
def _quit_tab2_widget(self):
quit = tk.Button(self,
text="QUIT at tab2",
command=root.destroy)
quit.pack()
def _hello(self):
print("Hello World at tab2")
if __name__ == '__main__':
root = tk.Tk()
app = Application(master=root)
app.mainloop()
widget の階層関係
- ttk.Notebook (window)
- tk.Frame (tab1)
- tk.Label (hello)
- tk.Button (quit)
- tk.Frame (tab2)
- tk.Button (hello)
- tk.Button (quit)
- tk.Button (quit)
- tk.Frame (tab1)