我正在使用

this代码在我的Tkinter上创建一个简单的日历.当我在主根窗口上放置日历时,日历显示正常.因此,我决定放置另一个按钮,它将创建一个Tkinter顶层窗口并在顶层窗口上放置另外一个日历.但这次它无法显示日历,而是它给了我这个错误,“TclError:无法打包. 18913120里面.18912200.18912400“.任何人都可以解释为什么我收到此错误消息.

这是我的示例代码:

import calendar

import sys

try:

import Tkinter

import tkFont

except ImportError: # py3k

import tkinter as Tkinter

import tkinter.font as tkFont

import ttk

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):

# XXX ToDo: cget and configure

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', '#ecffc4')

sel_fg = kw.pop('selectforeground', '#05640e')

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 and setup tags

# configure a canvas, and proper bindings, for selecting dates

self.__setup_selection(sel_bg, sel_fg)

# store items ids, used for insertion later

self._items = [self._calendar.insert('', 'end', values='')

for _ in range(6)]

# insert dates in the currently empty calendar

self._build_calendar()

# set the minimal size for the widget

self._calendar.bind('', 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 and its 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')

# the calendar

self._calendar = ttk.Treeview(show='', selectmode='none', height=7)

# 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')

self._calendar.insert('', 'end', values=cols, tag='header')

# adjust its columns width

font = tkFont.Font()

maxwidth = max(font.measure(col) for col in cols)

for col in cols:

self._calendar.column(col, width=maxwidth, minwidth=maxwidth,

anchor='e')

def __setup_selection(self, sel_bg, sel_fg):

self._font = tkFont.Font()

self._canvas = canvas = Tkinter.Canvas(self._calendar,

background=sel_bg, borderwidth=0, highlightthickness=0)

canvas.text = canvas.create_text(0, 0, fill=sel_fg, anchor='w')

canvas.bind('', lambda evt: canvas.place_forget())

self._calendar.bind('', lambda evt: canvas.place_forget())

self._calendar.bind('', 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 shown 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)

def _show_selection(self, text, bbox):

"""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)

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 not visible yet

return

# update and 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)

self._build_calendar() # reconstuct 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() # reconstruct 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]))

def myfunction():

root2=Tkinter.Toplevel(root)

ttkcal = Calendar(root2,firstweekday=calendar.SUNDAY)

ttkcal.pack(expand=1, fill='both')

root=Tkinter.Tk()

frame=Tkinter.Frame(root)

frame.pack(side="left")

button=Tkinter.Button(root,text="Top level",command=myfunction)

button.pack(side="right")

ttkcal = Calendar(frame,firstweekday=calendar.SUNDAY)

ttkcal.pack(expand=1, fill='both')

root.mainloop()

python中ttk和tkinter_Python tkinter与ttk日历相关推荐

  1. python中ttk和tkinter_python tkinter中ttk组件如何使用?

    大家有没有觉得我们在使用基础的tkinter模块,会不会感觉展现的页面效果比较单一呢?但是看到一些案例演示,又觉得展现效果还是比较炫酷的,其实这里不单单只是使用了模块,还利用了另一个进阶型模块--tt ...

  2. python中easygui和tkinter_python easygui Tkinter

    import easygui easygui.msgbox("HELLO LMDTX !")#使用按钮得到输入 import easygui a = easygui.buttonb ...

  3. python中label函数_python tkinter label标签怎么使用?

    终于有机会给大家介绍了label标签内容,想必很多小伙伴已经迫不及待听小编说这个最常见的标签函数了吧,大家之所以喜欢,主要还是依赖于这个标签是我们每一次的编程必备,看着大家如此喜欢这个函数,一进入控件 ...

  4. 四十八、Python中的GUI布局tkinter

    @Author:Runsen 现在极少有人会用上tkinter了,所以真正研究的人也就更少了,本来不想更新tkinter.看到很多人在学tkinter,其实用Python做布局,没有人这么干.但还是更 ...

  5. pythonguitkinter组件_四十八、Python中的GUI布局tkinter

    「@Author:Runsen」 现在极少有人会用上tkinter了,所以真正研究的人也就更少了,本来不想更新tkinter.看到很多人在学tkinter,其实用Python做布局,没有人这么干.但还 ...

  6. python中grid函数_python tkinter中的grid布局是什么?

    之前跟大家讲过登录界面是怎么设置的,但是被大家吐槽了一番,原因是因为设置的窗口状态并不好看,大家拿来了公认为比较好看的登录界面,希望可以设置出一样的效果,在python里没有什么是不可能实现的,因此, ...

  7. python中self image_Python3用tkinter和PIL实现看图工具

    需求 想做看图工具的,必然要支持jpg.png等常见格式,但tkinter是个纯粹的GUI库,不像GTK.QT那样大而全,所以只支持gif和ppm两种格式,局限很大,必须搭配图像处理库,才能实现基本的 ...

  8. python用户登录界面tkinter_python tkinter制作用户登录界面-Go语言中文社区

    学习一下莫烦Python的tkinter教程,根据教程制作了用户登录注册页.基本功能为检查登录.注册.清明上河图观看网址http://news.sohu.com/s2015/qmsht/index.s ...

  9. python中填充颜色结束的程序_在ttk/python中更改标签小部件的填充颜色

    我试图用python中的ttk/tkinter显示图像.图像有一个白色的边框,我想在一个更大的白色背景上显示这个图像,所以它周围有很多空白.在 为此,我在标签中使用"padx"和& ...

最新文章

  1. mate40能更新鸿蒙,Mate40领衔更新!鸿蒙系统首批升级机型名单:这些机型可坐等推送...
  2. 如何去掉CodeIgniter URL中的index.php
  3. BZOJ 2049: [Sdoi2008]Cave 洞穴勘测
  4. 使用Systemd包装SpringBoot应用
  5. ansible获取linux信息,ansible 获取系统信息的一些范例,ansible系统信息
  6. 从零开始学前端:形变(小游戏:3D翻滚盒子) --- 今天你学习了吗?(CSS:Day21)
  7. docker 镜像命令
  8. 总结定时器设计方法_PLC定时器(T)的工作原理及使用注意事项
  9. 数据结构(郝斌课程内容概述)
  10. python抓取网页数据时怎样显示进度条_Python 如何实时显示进度条?
  11. 浅谈产品原型制作与设计方法
  12. QQ安装包内置UE4是什么意义呢?会不会是奔着元宇宙,搭载了虚幻引擎的QQ在渲染数字孪生上表现更强劲?
  13. 【游戏设计模式】之三 状态模式、有限状态机 Unity版本实现
  14. ThreeJS 骨架图显示、骨骼修改颜色
  15. 什么是数字式KVM远程管理功能
  16. 游戏开发之Unity学习(五)——鼠标打飞碟(Hit UFO)
  17. python数据可视化案例 淘宝粽子_Python分析淘宝月饼销售数据,哪种最受欢迎?排第一的你想不到...
  18. SpringMVC--记录学习历程
  19. Meth | 关闭mac自带apache的启动
  20. uniapp开发获取用户位置信息功能解析

热门文章

  1. 链表 -- 双向循环链表(线性表)
  2. Ubuntu 16.04安装QQ(不一定成功)
  3. Adding a QR Code Reader in Flex on Android
  4. 关闭ubuntu启动时System Program Problem Detected提示
  5. ubuntu系统下载编译android源码
  6. SVO Without ROS环境搭建
  7. 【C++】LINK类型错误分析记录
  8. MATLAB【八】———— matlab 读取单个(多个)文件夹中所有图像
  9. I2C和SPI总线优缺点对比
  10. 为ASP.NET控件添加常用的JavaScript操作