我开始使用TkinterTable,但是我对Tkinter的功能却步步为营,所以我非常菜鸟。我正在尝试显示某些来源的数据,但我担心的是单元格似乎比文本短,并且我找不到找到使单元格适合文本大小的方法。这是我的代码:
from tkinter import *
from tkintertable import TableCanvas, TableModel
data = {'1': {'Source': 'OB', 'Campaign': 'X7765LKBTYYU-TAB-US', 'Impr.': 9457123, 'CTR': '0.12%', 'Spent': 45.78},
'2': {'Source': 'OB', 'Campaign': 'X6159TNFYTHY-PHONE-US-A', 'Impr.': 5456953, 'CTR': '0.27%', 'Spent': 12.52},
'3': {'Source': 'OB', 'Campaign': 'X7765LGKJHYRT-TAB-US', 'Impr.': 9457123, 'CTR': '0.12%', 'Spent': 45.78},
'4': {'Source': 'OB', 'Campaign': 'X6159FTJKYUKKX-PHONE-US-A', 'Impr.': 5456953, 'CTR': '0.27%', 'Spent': 12.52}
}
root= Tk()
tframe = Frame(root)
tframe.pack()
model = TableModel()
table = TableCanvas(tframe, model=model, data=data, editable=False, width=800, height=300)
table.show()
root.mainloop()
顺便说一句,这不是我的主要问题,但是如果您有快速解决的方法,将不胜感激。您会注意到,我在TableCanvas中具有“ editable = False”,但这似乎并不使单元格为只读,但我仍然可以对其进行编辑。知道为什么吗?
谢谢
答案 0 :(得分:0)
快速查看源py:
class TableCanvas(Canvas):
"""A tkinter class for providing table functionality"""
def __init__(self, parent=None, model=None, data=None, read_only=False,
width=None, height=None,
rows=10, cols=5, **kwargs):
...
def adjustColumnWidths(self):
"""Optimally adjust col widths to accomodate the longest entry
in each column - usually only called on first redraw"""
...
def autoResizeColumns(self):
"""Automatically set nice column widths and draw"""
...
对于您的第一个问题,看来adjustColumnWidths
方法未正确处理长字符串(可能是特定于平台的?)。无需过多研究,最简单的方法就是覆盖该方法:
class CustomCanvas(TableCanvas):
def adjustColumnWidths(self):
try:
fontsize = self.thefont[1]
except:
fontsize = self.fontsize
scale = 8.5 * float(fontsize)/12
for col in range(self.cols):
colname = self.model.getColumnName(col)
if colname in self.model.columnwidths:
w = self.model.columnwidths[colname]
else:
w = self.cellwidth
maxlen = self.model.getlongestEntry(col)
size = maxlen * scale
if size < w:
continue
#if size >= self.maxcellwidth:
# size = self.maxcellwidth
self.model.columnwidths[colname] = size*1.2 #I changed the calculation to a static float
return
然后使用CustomCanvas
代替您的TableCanvas
。
对于可编辑部分,不确定将editable
作为参数传递的想法。如果您使用read_only=True
,它将按预期工作。