我找到了这种现象的原因。当我在另一个脚本中自定义ttk.Treeview 小部件的样式时,我发现背景选项的值缺少# 符号。 ttk.Treeview图标默认不出现的现象是background选项的值语法错误造成的。
操作系统:Linux
测试代码重现语法错误导致的现象。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import tkinter as tk
import tkinter.ttk as ttk
class App(ttk.Frame):
def __init__(self, parent=None, *args, **kwargs):
super().__init__(parent)
self.parent = parent
# Create Treeview
self.tree = ttk.Treeview(self, column=('A', 'B'), selectmode='none', height=7)
self.tree.grid(row=0, column=0, sticky='nsew')
# Setup column heading
self.tree.heading('#0', text=' Pic directory', anchor='center')
self.tree.heading('#1', text=' A', anchor='center')
self.tree.heading('#2', text=' B', anchor='center')
# #0, #01, #02 denotes the 0, 1st, 2nd columns
# Setup column
self.tree.column('A', anchor='center', width=100)
self.tree.column('B', anchor='center', width=100)
# Insert image to #0
# change to your file path
self._img = tk.PhotoImage(file="./imagename.png")
self.tree.insert('', 'end', text="#0's text", image=self._img,
value=("A's value", "B's value"))
if __name__ == '__main__':
# Works
root = tk.Tk()
root.geometry('400x180+300+300')
app = App(root)
app.grid(row=0, column=0, sticky='nsew')
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
root.mainloop()
# Don't Works - syntax error in value of background causing missing icon
# in Treeview.
root = tk.Tk()
root.geometry('400x180+300+300')
style = ttk.Style()
style.configure('Treeview', background='303495') # should be '#303495'
app = App(root)
app.grid(row=0, column=0, sticky='nsew')
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
root.mainloop()