はじめに
Pythonで表をGUIで表示してくれるTreeViewを使ってみました。GUIにはTkinterを利用します。
やりたいこと
Tkinter
import tkinter as tk
from tkinter import ttk
main_win = tk.Tk()
main_win.title('Pizza List')
main_win.geometry('400x300')
# Treeviewを宣言
my_tree = ttk.Treeview(main_win)
main_win.mainloop()
Columnを定義
# Define Our Columns
my_tree['columns'] = ('Name', 'ID', 'Favorite Pizza')
Columnのフォーマットを定義
my_tree['columns'] = ('Name','ID','Favorite Pizza')
my_tree.column('#0',width=0, stretch='no')
my_tree.column('Name', anchor='w', width=120)
my_tree.column('ID',anchor='center', width=80)
my_tree.column('Favorite Pizza', anchor='w', width=120)
ColumnのHeadingを作成
# Create Heading
my_tree.heading('#0',text='Label',anchor='w')
my_tree.heading('Name', text='Name',anchor='w')
my_tree.heading('ID', text='ID', anchor='center')
my_tree.heading('Favorite Pizza',text='Favorite Pizza', anchor='w')
データを追加
# Add data
my_tree.insert(parent='', index='end', iid=0 ,values=('John',1,'Peperoni'))
my_tree.insert(parent='', index='end', iid=1 ,values=('Mary','2','Cheese'))
my_tree.insert(parent='', index='end', iid=2, values=('Tina','3','Ham'))
my_tree.insert(parent='', index='end', iid=3, values=('Bob','4','Supreme'))
my_tree.insert(parent='', index='end', iid=4, values=('Erin','5','Cheese'))
my_tree.insert(parent='', index='end', iid=5, values=('Wes','600','Onion'))
全体コード
import tkinter as tk
from tkinter import ttk
main_win = tk.Tk()
main_win.title('Pizza List')
main_win.geometry('400x300')
# Treeviewを宣言
my_tree = ttk.Treeview(main_win)
# Define Our Columns
my_tree['columns'] = ('Name', 'ID', 'Favorite Pizza')
# Formate Our Columns
my_tree['columns'] = ('Name','ID','Favorite Pizza')
my_tree.column('#0',width=0, stretch='no')
my_tree.column('Name', anchor='w', width=120)
my_tree.column('ID',anchor='center', width=80)
my_tree.column('Favorite Pizza', anchor='w', width=120)
# Create Heading
my_tree.heading('#0',text='Label',anchor='w')
my_tree.heading('Name', text='Name',anchor='w')
my_tree.heading('ID', text='ID', anchor='center')
my_tree.heading('Favorite Pizza',text='Favorite Pizza', anchor='w')
# Add data
my_tree.insert(parent='', index='end', iid=0 ,values=('John',1,'Peperoni'))
my_tree.insert(parent='', index='end', iid=1 ,values=('Mary','2','Cheese'))
my_tree.insert(parent='', index='end', iid=2, values=('Tina','3','Ham'))
my_tree.insert(parent='', index='end', iid=3, values=('Bob','4','Supreme'))
my_tree.insert(parent='', index='end', iid=4, values=('Erin','5','Cheese'))
my_tree.insert(parent='', index='end', iid=5, values=('Wes','600','Onion'))
# my_tree.move('6','0','0')
my_tree.pack(pady=20)
main_win.mainloop()
# https://www.youtube.com/watch?v=YTqDYmfccQU