Python ttk.Treeview-Can';不要改变行高
我正在使用可以找到的Python ttk.Treeview-Can';不要改变行高,python,python-2.7,python-3.x,tkinter,ttk,Python,Python 2.7,Python 3.x,Tkinter,Ttk,我正在使用可以找到的ttkcalendar.py 我已经对其进行了调整,以用于python3.3 基本上,我要做的是将这个日历小部件输入到我的Tkinter应用程序中,它运行良好,没有任何问题 我希望克服的问题是: 如何更改日历的字体大小(月、日和日期)-已完成 如何更改所选日期,使其变为bold-完成 如何更改treeview中的行高,如在prevoius尝试中,可以增加字体大小,但行高不随字体大小增加。-仍在等待帮助 提前谢谢 编辑1: 下面是整个程序的代码: import calendar
ttkcalendar.py
我已经对其进行了调整,以用于python3.3
基本上,我要做的是将这个日历小部件输入到我的Tkinter应用程序中,它运行良好,没有任何问题
我希望克服的问题是:
bold
-完成treeview
中的行高,如在prevoius尝试中,可以增加字体大小,但行高不随字体大小增加。-仍在等待帮助import calendar
import tkinter as Tkinter
import tkinter.font as tkFont
from tkinter import ttk #Imports ttk Module
def get_calendar(locale, fwday):
#Instantiate Proper Calendar Class
if locale is None:
return calendar.TextCalendar(fwday)
else:
return calendar.LocaleTextCalendar(fwday, locale)
class Calendar(ttk.Frame):
datetime = calendar.datetime.datetime
timedelta = calendar.datetime.timedelta
def __init__(self, master=None, **kw):
"""
WIDGET-SPECIFIC OPTIONS
locale, firstweekday, year, month, selectbackground,
selectforeground
"""
#Remove Custom Options From kw BEFORE Initializating ttk.Frame
fwday = kw.pop('firstweekday', calendar.MONDAY)
year = kw.pop('year', self.datetime.now().year)
month = kw.pop('month', self.datetime.now().month)
locale = kw.pop('locale', None)
sel_bg = kw.pop('selectbackground', '#EEEEEE')
sel_fg = kw.pop('selectforeground', '#B6333B')
self._date = self.datetime(year, month, 1)
self._selection = None #No Date Selected
ttk.Frame.__init__(self, master, **kw)
self._cal = get_calendar(locale, fwday)
self.__setup_styles() #Creates Custom Styles
self.__place_widgets() #Pack/Grid Used Widgets
self.__config_calendar() #Adjust Calendar Columns & Setup Tags
#Configure a Canvas & Proper Bindings for Selecting Dates
self.__setup_selection(sel_bg, sel_fg)
#Store Item ids - Used for Insertion Later On
self._items = [self._calendar.insert('', 'end', values='')
for _ in range(6)]
#Insert Dates in the Currently Empty Calendar
self._build_calendar()
#Set Minimal Size for Widget
self._calendar.bind('<Map>', self.__minsize)
def __setitem__(self, item, value):
if item in ('year', 'month'):
raise AttributeError("attribute '%s' is not writeable" % item)
elif item == 'selectbackground':
self._canvas['background'] = value
elif item == 'selectforeground':
self._canvas.itemconfigure(self._canvas.text, item=value)
else:
ttk.Frame.__setitem__(self, item, value)
def __getitem__(self, item):
if item in ('year', 'month'):
return getattr(self._date, item)
elif item == 'selectbackground':
return self._canvas['background']
elif item == 'selectforeground':
return self._canvas.itemcget(self._canvas.text, 'fill')
else:
r = ttk.tclobjs_to_py({item: ttk.Frame.__getitem__(self, item)})
return r[item]
def __setup_styles(self):
#CUSTOM ttk Styles
style = ttk.Style(self.master)
arrow_layout = lambda dir: (
[('Button.focus', {'children': [('Button.%sarrow' % dir, None)]})]
)
style.layout('L.TButton', arrow_layout('left'))
style.layout('R.TButton', arrow_layout('right'))
def __place_widgets(self):
#Header Frame & Widgets
hframe = ttk.Frame(self)
lbtn = ttk.Button(hframe, style='L.TButton', command=self._prev_month)
rbtn = ttk.Button(hframe, style='R.TButton', command=self._next_month)
self._header = ttk.Label(hframe, width=15, anchor='center', font='Arial 20')
#Main Calendar
self._calendar = ttk.Treeview(show='', selectmode='none', height='6')
#Pack The Widgets
hframe.pack(in_=self, side='top', pady=4, anchor='center')
lbtn.grid(in_=hframe)
self._header.grid(in_=hframe, column=1, row=0, padx=12)
rbtn.grid(in_=hframe, column=2, row=0)
self._calendar.pack(in_=self, expand=1, fill='both', side='bottom')
def __config_calendar(self):
cols = self._cal.formatweekheader(3).split()
self._calendar['columns'] = cols
self._calendar.tag_configure('header', background='grey90', font='Arial 20')
self._calendar.insert('', 'end', values=cols, tag=('header', 'dayFont'))
#Change Font of dayFont TAG
self._calendar.tag_configure('dayFont', font='Arial 20')
#Adjust Column Widths
font = tkFont.Font(size=20)
maxwidth = max(font.measure(col) for col in cols)
for col in cols:
self._calendar.column(col, width=maxwidth, minwidth=maxwidth, anchor='c')
def __setup_selection(self, sel_bg, sel_fg):
self._font = tkFont.Font()
canvas = Tkinter.Canvas(self._calendar, background=sel_bg, borderwidth=0, highlightthickness=0)
self._canvas = canvas
canvas.text = canvas.create_text(0, 0, fill=sel_fg, anchor='c')
canvas.bind('<ButtonPress-1>', lambda evt: canvas.place_forget())
self._calendar.bind('<Configure>', lambda evt: canvas.place_forget())
self._calendar.bind('<ButtonPress-1>', self._pressed)
def __minsize(self, evt):
width, height = self._calendar.master.geometry().split('x')
height = height[:height.index('+')]
self._calendar.master.minsize(width, height)
def _build_calendar(self):
year, month = self._date.year, self._date.month
#Update Header Text (Month, YEAR)
header = self._cal.formatmonthname(year, month, 0)
self._header['text'] = header.title()
#Update Calendar Showing Dates
cal = self._cal.monthdayscalendar(year, month)
for indx, item in enumerate(self._items):
week = cal[indx] if indx < len(cal) else []
fmt_week = [('%02d' % day) if day else '' for day in week]
self._calendar.item(item, values=fmt_week, tag='bodyFont')
self._calendar.tag_configure('bodyFont', font='Arial 10')
def _show_selection(self, text, bbox): #SELECTION FONT
"""Configure canvas for a new selection."""
x, y, width, height = bbox
textw = self._font.measure(text)
canvas = self._canvas
canvas.configure(width=width, height=height)
canvas.coords(canvas.text, width - textw, height / 2 - 1)
canvas.itemconfigure(canvas.text, text=text, font='Arial 15 bold')
canvas.place(in_=self._calendar, x=x, y=y)
#Callbacks
def _pressed(self, evt):
"""Clicked somewhere in the calendar."""
x, y, widget = evt.x, evt.y, evt.widget
item = widget.identify_row(y)
column = widget.identify_column(x)
if not column or not item in self._items: #Clicked in the Weekdays Row or Just Outside The Columns
return
item_values = widget.item(item)['values']
if not len(item_values): #Row is Empty For This Month
return
text = item_values[int(column[1]) - 1]
if not text: #Date is Empty
return
bbox = widget.bbox(item, column)
if not bbox: #Calendar is not Visible Yet
return
#Update & Then Show Selection
text = '%02d' % text
self._selection = (text, item, column)
self._show_selection(text, bbox)
def _prev_month(self):
"""Updated calendar to show the previous month."""
self._canvas.place_forget()
self._date = self._date - self.timedelta(days=1)
self._date = self.datetime(self._date.year, self._date.month, 1)
#Reconstruct Calendar
self._build_calendar()
def _next_month(self):
"""Update calendar to show the next month."""
self._canvas.place_forget()
year, month = self._date.year, self._date.month
self._date = self._date + self.timedelta(
days=calendar.monthrange(year, month)[1] + 1)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar()
#Properties
#-----------------------------------------------------
@property
def selection(self):
"""Return a datetime representing the current selected date."""
if not self._selection:
return None
year, month = self._date.year, self._date.month
return self.datetime(year, month, int(self._selection[0]))
#----------------------------------
导入日历
将tkinter作为tkinter导入
将tkinter.font作为tkFont导入
从tkinter导入ttk#导入ttk模块
def get_日历(区域设置,工作日):
#实例化适当的日历类
如果区域设置为“无”:
返回日历。文本日历(fwday)
其他:
return calendar.LocaleTextCalendar(fwday,locale)
课程日历(ttk.Frame):
datetime=calendar.datetime.datetime
timedelta=calendar.datetime.timedelta
def _初始功率(自,主=无,**kw):
"""
特定于小部件的选项
地区、第一个工作日、年、月、选择背景、,
选择前景
"""
#在初始化ttk.Frame之前,从kw中删除自定义选项
fwday=kw.pop('第一个工作日',日历.星期一)
year=kw.pop('year',self.datetime.now().year)
month=kw.pop('month',self.datetime.now().month)
locale=kw.pop('locale',无)
sel_bg=kw.pop('selectbackground','eeeeeeee'))
sel_fg=kw.pop('selectforeground','B6333B')
self.\u date=self.datetime(年、月、1)
self._selection=无#未选择日期
ttk.帧。\uuuuu初始\uuuuuuuuuuuuuuuuuuuuu(自,主,**kw)
self.\u cal=get\u日历(区域设置,工作日)
self.u设置_样式()#创建自定义样式
self.u place_widgets()#打包/网格使用的widgets
self._config_calendar()#调整日历列和设置标记
#为选择日期配置画布和适当的绑定
自我设置选择(选择背景、选择前景)
#存储项ID-用于以后插入
self.\u items=[self.\u calendar.insert('''end',values='')
对于uu在范围内(6)]
#在当前空日历中插入日期
self.\u build\u calendar()
#设置小部件的最小大小
self.\u calendar.bind(“”,self.\u minsize)
定义设置项(自身、项、值):
如果项目在('年'、'月'):
raise AttributeError(“属性“%s”不可写”%item)
elif项==“selectbackground”:
self._canvas['background']=值
elif项==“选择前景”:
self.\u canvas.itemconfigure(self.\u canvas.text,item=value)
其他:
ttk.Frame.\uuuuu设置项目\uuuuuuu(自身、项目、值)
定义获取项目(自身,项目):
如果项目在('年'、'月'):
返回getattr(自身日期,项目)
elif项==“selectbackground”:
返回自我。_画布['background']
elif项==“选择前景”:
返回self.\u canvas.itemcget(self.\u canvas.text,“fill”)
其他:
r=ttk.tclobjs_to_py({item:ttk.Frame.\uuuuu getitem_uuu(self,item)})
返回r[项目]
定义设置样式(自):
#自定义ttk样式
style=ttk.style(self.master)
arrow_layout=lambda dir:(
[('Button.focus',{'children':[('Button.%sarrow'%dir,None]}]
)
style.layout('L.TButton',arrow_布局('left'))
样式布局('R.TButton',箭头布局('right'))
def_u_uplace_小部件(自):
#标题框架和小部件
hframe=ttk.帧(自)
lbtn=ttk.按钮(hframe,style='L.TButton',command=self.\u上个月)
rbtn=ttk.按钮(hframe,style='R.TButton',command=self.\u下个月)
self.\u header=ttk.Label(hframe,宽度=15,锚定class='center',font='Arial 20')
#主日历
self.\u calendar=ttk.Treeview(show='',selectmode='none',height='6')
#打包小部件
hframe.pack(in_uz=self,side='top',pady=4,anchor='center')
lbtn.网格(in=hframe)
self._header.grid(in_u=hframe,column=1,row=0,padx=12)
rbtn.grid(在=hframe中,列=2,行=0)
self.\u calendar.pack(in=self,expand=1,fill='both',side='bottom')
定义配置日历(自):
cols=self.\u cal.formatweekheader(3).split()
self.\u日历['columns']=cols
self.\u calendar.tag\u configure('header',background='grey90',font='Arial 20')
self._calendar.insert(“”,'end',values=cols,tag=('header','dayFont'))
#更改dayFont标记的字体
self.\u calendar.tag\u configure('dayFont',font='Arial 20')
#调整列宽
font=tkFont.font(大小=20)
maxwidth=max(col中col的字体度量(col))
对于col中的col:
self.\u calendar.column(col,width=maxwidth,minwidth=maxwidth,anchor='c')
定义设置选择(自、选择背景、选择前景):
self.\u font=tkFont.font()
canvas=Tkinter.canvas(self.\u日历,背景=sel\u背景,边框宽度=0,高亮厚度=0)
self.\u canvas=canvas
canvas.text=canvas.create_text(0,0,fill=sel_fg,anchor='c')
canvas.bind(“”,lambda evt:canvas.place_-forget())
self.\u calendar.bind(“”,lambda evt:canvas.place\u forget())
self.\u日历.绑定(“”,self.\u按)
def__minsize(自我,evt):
宽度,高度=self.\u calendar.master.geometry().split('x'))
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.geometry('500x200')
style = ttk.Style(root)
style.configure('Treeview', rowheight=40) #SOLUTION
tree = ttk.Treeview(root)
tree.insert('', 0, text='Line 1 of many XXX', tags='T')
tree.insert('', 1, text='Line 2 of many XXX', tags='T')
tree.insert('', 2, text='Line 3 of many XXX', tags='T')
tree.column('#0', stretch=True)
tree.tag_configure('T', font='Arial 20')
tree.pack(fill='x')
style.configure('Calendar.Treeview', rowheight=40)
tree = ttk.Treeview(root, style='Calendar.Treeview')
>>> style.layout('Calendar.Treeview')
[('Treeview.field', {'sticky': 'nswe', 'children': [('Treeview.padding',
{'sticky': 'nswe', 'children': [('Treeview.treearea', {'sticky': 'nswe'})]})], 'border': '1'})]
>>> style.element_options('Calendar.Treeview.border')
('-relief',)
>>> style.lookup('Calendar.Treeview.border', 'relief')
''
>>> style.configure('Calendar.Treeview.border', relief='raised')
{}
#apply any configuration options
ttk.Style().configure('Treeview',rowheight=30)
try:
from tkinter.font import Font
from tkinter.ttk import Style, Treeview
from tkinter import *
except:
from tkFont import Font
font ttk import Style, Treeview
from Tkinter import *
font=Font(family='Arial', size=20)
font.metrics()
#output: {'ascent': 31, 'descent': 7, 'linespace': 38, 'fixed': 0}
font.metrics()['linespace']
#output: 38
fontheight=font.metrics()['linespace']
style=Style()
style.configure('Calendar.Treeview', font=font, rowheight=fontheight)
tree=Treeview(style='Calendar.Treeview')
def scaleup():
font['size']+=1
style.configure('Calendar.Treeview', rowheight=font.metrics()['linespace'])
def scaledown():
font['size']-=1
style.configure('Calendar.Treeview', rowheight=font.metrics()['linespace'])
tree.bind('<Control-equal>', scaleup)
tree.bind('<Control-minus>', scaledown)