Python Tkinter Treeview Widget Error: 'module 'tkinter' has no attribute 'treeview''
The error 'AttributeError: module 'tkinter' has no attribute 'treeview'' occurs when you try to use the Treeview widget in Python Tkinter with an incorrect syntax. The correct name for the widget is ttk.Treeview, not tk.treeview.
Here's the breakdown of the error and how to fix it:
-
The Error: The error message
'AttributeError: module 'tkinter' has no attribute 'treeview''indicates that you're trying to access a widget named 'treeview' within thetkintermodule. However,tkinterdoesn't have a widget by that name. -
The Solution: The correct widget to use is the
Treeviewwidget, which is located in thettk(themed Tkinter) module.
Code Example
import tkinter as tk
from tkinter import ttk
def zonghechaxunwindow():
window = tk.Tk()
def select1():
tree = ttk.Treeview(window)
tree['columns'] = ('id', 'name', 'gender', 'phone', 'address', 'remark')
tree.column('id', width=90)
tree.column('name', width=90)
tree.column('gender', width=90)
tree.column('phone', width=90)
tree.column('address', width=90)
tree.column('remark', width=90)
tree.heading('id', text='身份证号')
tree.heading('name', text='姓名')
tree.heading('gender', text='性别')
tree.heading('phone', text='联系电话')
tree.heading('address', text='家庭住址')
tree.heading('remark', text='职位')
tree.grid(column=0, row=1, sticky='NSEW')
conn = py.connect(host='localhost', user='root', password='houyushan1022', db='police')
cursor = conn.cursor()
cursor.execute('select * from person_info where 家庭住址='北京市朝阳区'')
list_result = cursor.fetchall()
x = tree.get_children()
for item in x:
tree.delete(item)
for i in range(len(list_result)):
tree.insert('', i, text=str(i), values=(list_result[i][0], list_result[i][1], list_result[i][2], list_result[i][3], list_result[i][4], list_result[i][5]))
conn.commit()
conn.close()
select_button1 = tk.Button(window, bg='pink', text='查询家在北京朝阳区的民警', font=('微软雅黑 -20'), width=40, height=1, command=select1)
select_button1.place(x=10, y=370)
window.mainloop()
zonghechaxunwindow()
Explanation
-
Import ttk: Make sure to import the
ttkmodule at the beginning of your script. -
Use ttk.Treeview: Replace
tree=tk.treeview(window)withtree=ttk.Treeview(window).
By correcting the syntax and using the ttk.Treeview widget, you will resolve the 'AttributeError' and be able to successfully implement the Treeview widget in your Tkinter application.
原文地址: https://www.cveoy.top/t/topic/osqN 著作权归作者所有。请勿转载和采集!