当前位置: 首页 > 编程日记 > 正文

python中ttk和tkinter_Python tkinter与ttk日历

我正在使用

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

相关文章:

Ubuntu dns

在Ubuntu系统网络设备启动的流程中&#xff0c;会依赖/etc/network/interface的配置文件初始化网络接口&#xff0c;所以直接在/etc/network/interface之中配置好对应的dns服务器会最先写入/etc/resolv.conf。所以我们可以在其中添加如下内容&#xff1a; dns-nameserve…

web图片识别

<!doctype html><html lang"en"><head> <meta charset"UTF-8"> <title>图像识别</title> <script src"../js/jquery.js"></script></head><body><canvas id"canv…

通俗易懂,到底什么是区块链?

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自区块链技术社区&#xff0c;未经允许拒绝转载。 2017年9月4日&#xff0c;中国政府正式明令禁止ICO和数字货币交易行为&#xff0c;随即关闭了多个数字货币交易所。同时政府也多次声明&#xff0…

select三级联动 怎么删除前一个的_python测试开发django57.xadmin选项二级联动

前言当我们选择项目分类的时候&#xff0c;一个项目下关联多个模块&#xff0c;同时有这两个选项框的时候&#xff0c;需要实现选中一个项目&#xff0c;模块里面自动删除出该项目下的模块&#xff0c;如下图这种解决基本思路&#xff1a;1.写个jqeury脚本监听change事件2.ajax…

安装wdcp的方法和bug

1.Wdcp安装SSH登录系统,这里讲解源码编译安装和RPM包安装两种 a.源码编译安装 下载源码包wget http://dl.wdlinux.cn:5180/lanmp_laster.tar.gz 解压并安装 tar zxvf lanmp_laster.tar.gz sh in.sh linux安装wdcp之后mysql找不到my.cnf&#xff0c;locate my-medium.cnf。 cp /…

第七周读书笔记

《深入理解计算机系统》从程序设计与性能优化的角度介绍了计算机系统&#xff0c;让我从程序员的角度了解了计算机系统&#xff0c;更深入地理解了硬件、操作系统和编译系统等对应用程序性能和正确性的影响&#xff0c;并掌握了基本的程序优化设计技术&#xff0c;为编写更高效…

是什么限制了区块链技术的应用?

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自区块链技术社区&#xff0c;未经允许拒绝转载。 2017年已经匆匆离去&#xff0c;回顾过去一整年&#xff0c;似乎区块链应用一直处于隐忍未发的状态&#xff0c;很多项目的落地已处于验证阶段&…

软件包管理(rpmyum)

一、rpm包管理器 rpm是一个功能强大的包管理工具&#xff0c;可用于构建&#xff0c;安装&#xff0c;查询&#xff0c;验证&#xff0c;更新和卸载软件包。 用法&#xff1a; rpm [OPTION...] 配置文件&#xff1a; /var/lib/rpm/ 已安装rpm包的元数据 选项&#xff1a; -i&am…

python yield理解_对Python中Yield的理解

看到下面这段程序的时候&#xff0c;有点不明白这个yield到底是个啥东西&#xff0c;看了网上很多的博客&#xff0c;大致理解了yield的含义&#xff0c;所以记录下来。要说yield首先要说python中的生成器&#xff0c;那么什么是生成器?假设有一个包含一百万个元素的列表&…

Linux下文件的三种时间戳

Linux下文件的三种时间标记 三种时间对应关系表 columncolumncolumn访问时间Accessatime修改时间Modifymtime状态改动时间Changectime如何查看文件文件的三种时间戳 stat filename 三种时间戳的解释 访问时间&#xff1a;读一次文件的内容&#xff0c;这个时间就会更新。比如mo…

比特币和以太坊本质有什么区别?

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自区块链技术社区&#xff0c;未经允许拒绝转载。 14年的时候&#xff0c;币圈 &#xff08;当时还没有链圈之说&#xff0c;链圈应该是17年的事情了&#xff0c;区块链概念的流行是15年底&#xf…

HDU1402(FFT入门)

题目链接&#xff1a;http://acm.hdu.edu.cn/status.php?userReykjavik11207&pid1402&status5 本题数据范围为5e4&#xff0c;常规方法O(n2)肯定是不行的。 FFT是离散傅里叶变换DFT的快速形式 对多项式f(x) a0 a1x a2x2 an-1xn-1&#xff0c;有两种表示法&#x…

python怎么读_如何用Python读写文件

前面我们已经介绍了很多Python相关的基础知识&#xff0c;大家是不是对Python已经有了进一步认识了呢&#xff1f;作为人工智能时代的热门编程语言&#xff0c;开始接触并学习Python的孩子越来越多&#xff0c;家长们都不想让自己的孩子落于人后&#xff0c;近期前来找陈老师咨…

什么是区块链智能合约?

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自区块链技术社区&#xff0c;未经允许拒绝转载。 自从2009年第一枚比特币诞生&#xff0c;九年多时间里&#xff0c;区块链技术正在被应用在人们生活的各方各面&#xff0c;从1.0时代的数字货币&…

python数据分析基础 余本国_Python数据分析基础

本书根据作者多年教学经验编写, 条理清楚, 内容深浅适中, 尽量让读者从实例出发, 结合课后练习, 少走弯路。本书涉及的内容主要包括Python数据类型与运算、流程控制及函数与类、Pandas库的数据处理与分析等。作者通过近三轮的教学&#xff0c;对Python3.x的基础知识进行了筛选和…

stm32F042 (二) 按键触发中断

已经实现GPIO口输出高低电平控制LED&#xff0c;这里实现按键触发中断来改变LED闪亮的频率&#xff0c;因为PB3连着LED&#xff0c;所以PB3的输出模式没有改变&#xff0c;随意选一个GPIO口PA7接按键产生中断。因为nucleo开发板是裸板&#xff0c;所以按键、上拉电阻是另找在面…

区块链和智能合约的关系

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自区块链技术社区&#xff0c;未经允许拒绝转载。 尽管比特币&#xff08;Bitcoin&#xff09;和以太坊&#xff08;Ethereum&#xff09;是经常被一起提及的两个词&#xff0c;但实际上&#xff0…

repo同步代码_iTOP-4412开发板android4.0代码下载和编译

Android4.0 源码可以从光盘&#xff0c;网盘获取稳定版本&#xff0c;也可以从 GitHub 下载我们的开发版本。GitHub 仅提供源码下载&#xff0c;不提供二进制下载&#xff0c;二进制文件存放在光盘和网盘中。基于迅为4412开发板6.3.1.1 repo 下载android 代码管理不同于 uboot,…

vue项目构建实战基础知识:SPA理解/RESTful接口介绍/static目录配置/axios封装/打包时map文件去除...

一、SPA 不是指水疗。是 single page web application 的缩写。中文翻译为 单页应用程序 或 单页Web应用&#xff0c;更多解释请自行搜索。 所有的前端人员都应该明白我们的页面的 url 构成&#xff1a;http://www.fengcms.com/index.html?namefungleo&old32#mylove/is/wo…

神奇的输入 while(cin....)如何在遇见换行之后进入下一层循环读入

1 cin>>m>>n;2 for(int i1;i<m;i){4 int x0;5 char ch ;6 while(ch!10) //在遇到换行之后进入下一层循环读入。7 {8 x;9 cin>>c[x]; 10 chgetchar(); 11 } 神奇的输入。 get skill&#xff01;转载于:https://www.cnblogs.com/zyker/p/588…

区块链中的“智能合约”有何应用?

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自区块链技术社区&#xff0c;未经允许拒绝转载。 如刺金般闪耀的区块链时代&#xff0c;投资者的热潮还将持续升温&#xff0c;与此同时金融的大佬已经开始注意到区块链应用落地场景的实现&#xff…

米勒罗宾素性测试(Miller–Rabin primality test)

1 #include<iostream> //该程序为哥德巴赫猜&#xff08;想输出所有的组合&#xff09;2 #include<cmath>3 #include<cstdlib>4 #include<ctime>5 #include<cstdio>6 7 using namespace std;8 9 typedef unsigned long long ull; 10 typedef u…

Linux Linux程序练习十一(网络编程大文件发送UDP版)

//网络编程发送端--大文件传输&#xff08;UDP&#xff09; #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h>#include <sys/types.h> #include <sys/socket.h> #include <n…

iic通信原理_电子知识之IIC通信原理和协议分享

IIC 的一些特征&#xff1a; 两条总线&#xff1a;串行数据总线(SDA)和串行时钟总线(SCL)真正的多主机总线连接到相同总线的ic数量只受到总线的最大电容400pF限制。串行8位双向数据在标准模式下可达100K bit/s快速模式400K bit/s,高速模式下3.4Mbit/s.数据有效性规定&#xff1…

以太坊核心概念

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自区块链技术社区&#xff0c;未经允许拒绝转载。 以太坊虚拟机&#xff08;EVM&#xff09; 以太坊虚拟机&#xff08;EVM&#xff09;是以太坊中智能合约的运行环境。它不仅被沙箱封装起来&#…

使用rest_framework写api接口的一些注意事项(axios发送ajax请求)

1. 类继承GenericAPIView&#xff0c;定义queryset 印象深刻的事&#xff1a;由于原来对于继承关系不太清楚&#xff0c;写接口 APIView/泛指GenericAPIView不太关注queryset没有设置渲染器&#xff1a;默认 [JSONRenderer,BrowsableAPIRenderer]BrowsableAPIRenderer&#xff…

iir数字滤波器_手把手教系列之一阶数字滤波器设计实现(附代码)

[导读] 前面分享了 IIR/FIR/mean/梳状数字滤波器的具体设计实现&#xff0c;这几种使用起来或许觉得计算量大&#xff0c;相对复杂。实际工程应用中通常有必要过滤来自传感器或音频流的数据&#xff0c;以抑制不必要的噪声。有的应用场景&#xff0c;可能只需要一个最简单的一阶…

正则表达式中$1,$2 ===算是什么意思

$1,$2...是表示的小括号里的内容 $1是第一个小括号里的 ,$2是第2个小括号里的 比如 /gai([\w]?)over([\d])/ 匹配 gainover123 $1 括号里的 n $2 第2个括号里的 123转载于:https://www.cnblogs.com/vertko/p/5888902.html

为什么以太坊能成为区块链2.0的代表之作?

链客&#xff0c;专为开发者而生&#xff0c;有问必答&#xff01; 此文章来自区块链技术社区&#xff0c;未经允许拒绝转载。 区块链的学习进入到第四天&#xff0c;前三天学习比特币&#xff0c;分别从比特币的前世、货币属性和背后的区块链技术学习。 比特币是区块链的1…

(转)搭建企业内部yum仓库(centos6+centos7+epel源)

搭建企业内部yum仓库(centos6centos7epel源) 原文&#xff1a;https://www.cnblogs.com/nulige/p/6081192.html https://www.linuxidc.com/Linux/2017-11/148723.htm---------部署yum仓库与定制rpm包 1. 创建yum仓库目录mkdir -p /data/yum_data/cd /data/yum_data/#可以上传rp…