python--以窗口或者canvas为父容器的另一种情况

from tkinter import *
from tkinter import ttk
root = Tk()
canvas = Canvas(root)
tree = ttk.Treeview(canvas, show='headings')  # 表格
canvas.grid(row=0, column=0)

tree["columns"] = ("姓名", "年龄", "身高")
tree.heading("姓名", text="姓名")  # 显示表头
tree.heading("年龄", text="年龄")
tree.heading("身高", text="身高")
tree.column("姓名", width=100, anchor="center")
tree.column("年龄", width=100, anchor="center")
tree.column("身高", width=800, anchor="center")
MON_FONTSIZE = 15
style = ttk.Style()
style.configure('Treeview.Heading', font=(None, MON_FONTSIZE),
                rowheight=int(MON_FONTSIZE * 5.2))
style.configure('Treeview', font=(None, MON_FONTSIZE),
                rowheight=int(MON_FONTSIZE * 5.2))
tree.tag_configure("first", foreground="red")
tree.tag_configure("second", foreground="blue")

arr = [{'type': 'player', 'msg': '0.017s 玩家 攻击 1级小怪:6 点伤害,小怪血量51/86'},
       {'type': 'enemy', 'msg': '0.017s 9级小怪 攻击 玩家:13 点伤害,玩家血量502/515'},
       {'type': 'enemy', 'msg': '0.017s 7级小怪 攻击 玩家:9 点伤害,玩家血量493/515'},
       {'type': 'enemy', 'msg': '0.017s 9级小怪 攻击 玩家:13 点伤害,玩家血量502/515'},
       {'type': 'enemy', 'msg': '0.017s 7级小怪 攻击 玩家:9 点伤害,玩家血量493/515'}
    , {'type': 'enemy', 'msg': '0.017s 9级小怪 攻击 玩家:13 点伤害,玩家血量502/515'},
       {'type': 'enemy', 'msg': '0.017s 7级小怪 攻击 玩家:9 点伤害,玩家血量493/515'},
       {'type': 'enemy', 'msg': '0.017s 9级小怪 攻击 玩家:13 点伤害,玩家血量502/515'},
       {'type': 'enemy', 'msg': '0.017s 7级小怪 攻击 玩家:9 点伤害,玩家血量493/515'}
    , {'type': 'enemy', 'msg': '0.017s 9级小怪 攻击 玩家:13 点伤害,玩家血量502/515'},
       {'type': 'enemy', 'msg': '0.017s 7级小怪 攻击 玩家:9 点伤害,玩家血量493/515'},
       {'type': 'enemy', 'msg': '0.017s 9级小怪 攻击 玩家:13 点伤害,玩家血量502/515'},
       {'type': 'enemy', 'msg': '0.017s 7级小怪 攻击 玩家:9 点伤害,玩家血量493/515'}
    ,
       {'type': 'enemy', 'msg': '0.017s 9级小怪 攻击 玩家:13 点伤害,玩家血量502/515'},
       {'type': 'enemy', 'msg': '0.017s 7级小怪 攻击 玩家:9 点伤害,玩家血量493/515'}
    , {'type': 'enemy', 'msg': '0.017s 9级小怪 攻击 玩家:13 点伤害,玩家血量502/515'},
       {'type': 'enemy', 'msg': '0.017s 7级小怪 攻击 玩家:9 点伤害,玩家血量493/515'},
       {'type': 'enemy', 'msg': '0.017s 9级小怪 攻击 玩家:13 点伤害,玩家血量502/515'},
       {'type': 'enemy', 'msg': '0.017s 7级小怪 攻击 玩家:9 点伤害,玩家血量493/515'},
       {'type': 'enemy', 'msg': '0.017s 9级小怪 攻击 玩家:13 点伤害,玩家血量502/515'},
       {'type': 'enemy', 'msg': '0.017s 7级小怪 攻击 玩家:9 点伤害,玩家血量493/515'}]
index = 0
for item in arr:  # 写入数据
    if index == 0:
        tree.insert('', index, values=(item.get("type"), item.get("player"), item.get("msg")), tags="first")
    else:
        tree.insert('', index, values=(item.get("type"), item.get("enemy"), item.get("msg")), tags="second")
    index += 1
tree.pack()
vbar = ttk.Scrollbar(canvas, orient=VERTICAL, command=tree.yview)
tree.configure(yscrollcommand=vbar.set)
tree.grid(row=0, column=0, sticky=NSEW)
vbar.grid(row=0, column=1, sticky=NS)
root.mainloop()

红色字体部分很重要,否则滚动条无法生效

原文地址:https://www.cnblogs.com/LindaBlog/p/13931444.html