Python3 tk TreeView动态列宽

时间:2015-07-14 14:50:29

标签: python-3.x dynamic tkinter treeview ttk

相关代码如下。我正在寻找一种动态调整ttk TreeView小部件列的方法以适应其中的文本。我目前有一个TreeView(在一个类中),所有列都有最小宽度,但填充“notes”列的文本可能无限长,并且列需要调整大小以获取该字符串。我最终将限制最大大小,但不用说我仍然希望它在需要时保持大量文本是动态的,但在字符串较短时也要整洁。

确实有两种解决方案,无论是动态调整大小还是计算给定字符串所需的像素宽度,都提到了font.measure(),但这似乎不适用于python 3.x

任何帮助都会很棒,我想把这个小东西分类,这样我就可以完成了!

 with sql.connect(dbFile) as dbConnection:
        cursor = dbConnection.cursor()
        self.treeStudentLog = ttk.Treeview(self.mainFrame, columns=("type","points", "notes"), height=21)

        yscrollbar = ttk.Scrollbar(self.mainFrame, orient='vertical', command=self.treeStudentLog.yview)
        xscrollbar = ttk.Scrollbar(self.mainFrame, orient='horizontal', command=self.treeStudentLog.xview)

        yscrollbar.place(x=822, y=240, height=440)
        xscrollbar.place(x=10, y=678, width=813)

        self.treeStudentLog.configure(yscroll=yscrollbar.set, xscroll=xscrollbar.set)

        self.treeStudentLog.heading("#0", text="Student")
        self.treeStudentLog.column("#0", minwidth=180) 

        self.treeStudentLog.heading("type", text="Log Type")
        self.treeStudentLog.column("type", minwidth=160)           

        self.treeStudentLog.heading("points", text="Points")
        self.treeStudentLog.column("points", minwidth=60)

        self.treeStudentLog.heading("notes", text="Teacher Comments")

        #populate the student log
        cursor.execute("SELECT * FROM studentlogs ORDER BY logID DESC LIMIT 100")
        allLogs = cursor.fetchall()

        noteLength = 0

        for log in allLogs:
            logNotes = log[3]
            print(type(logNotes))
            try:
                if len(logNotes) > noteLength:
                    noteLength = len(logNotes)
            except:
                noteLength = noteLength

            cursor.execute("SELECT * FROM users WHERE userID = ?", (log[2],))
            studentDetails = cursor.fetchone()

            cursor.execute("SELECT * FROM logtypes WHERE typeID = ?", (log[1],))
            logTypeDetails = cursor.fetchone()

            logDesc = logTypeDetails[2]
            logValue = logTypeDetails[1]

            studentName = studentDetails[1] + " " + studentDetails[2]
            self.treeStudentLog.insert('', 'end', text=studentName, values=(logDesc, logValue, logNotes))

        self.treeStudentLog.column("notes", minwidth=noteLength * 8)


        self.treeStudentLog.place(x=10, y=240, width=812)

编辑:我用来定义字体的代码:

import tkinter as tk
from tkinter import font

treeFont = font(self.mainWindow, "Calibri", "12")

其中self.mainWindow是当前的顶级窗口(不是root,但我也尝试过)。我也尝试过tk.font(blah)同样的效果。

我最终得到一个TypeError“module”对象不可调用

0 个答案:

没有答案