鱼C论坛

 找回密码
 立即注册
查看: 378|回复: 4

[已解决]Tkinter 创建日历

[复制链接]
发表于 2024-9-7 15:45:34 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. from tkinter import *
  2. import calendar
  3. root=Tk()
  4. b=Button(root,
  5.           text=calendar.month(2025,9),
  6.           foreground="navy",
  7.           background="bisque",
  8.           font="汉仪长艺体简 22 ",
  9.           relief="groove",
  10.           borderwidth=12)
  11. b.pack()
  12. mainloop()
复制代码


为什么29日、30日不能对齐 ?

最佳答案
2024-9-7 16:01:48
这样~
  1. from tkinter import *
  2. import calendar
  3. root=Tk()
  4. b=Button(root,
  5.          text=calendar.month(2025,9),
  6.          foreground="navy",
  7.          background="bisque",
  8.          font="汉仪长艺体简 22 ",
  9.          relief="groove",
  10.          borderwidth=12,
  11.          justify=LEFT)
  12. b.pack()
  13. mainloop()
复制代码
24.png
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2024-9-7 15:49:42 | 显示全部楼层
在 Tkinter 中使用 `calendar.month()` 来生成月份的字符串时,生成的日历格式通常包含了一些空格和换行符,而且每月天数的排列格式不固定,这会导致在 Tkinter 的按钮上显示时,不同长度的文本行可能产生无法对齐的现象。

如果希望日历的显示能够对齐,建议使用 `Label` 小部件,结合 `Text` 小部件更好控制格式,而不是直接用 `Button`。以下是一个改进的示例代码,它使用 `Label` 小部件来实现显示效果:

  1. from tkinter import *
  2. import calendar

  3. root = Tk()

  4. # 获取 2025 年 9 月的日历
  5. cal_text = calendar.month(2025, 9)

  6. # 创建 Label 小部件来显示日历
  7. calendar_label = Label(root,
  8.                        text=cal_text,
  9.                        foreground="navy",
  10.                        background="bisque",
  11.                        font=("Courier", 12),  # 使用等宽字体使对齐更容易
  12.                        relief="groove",
  13.                        borderwidth=12,
  14.                        justify=LEFT  # 左对齐
  15.                     )

  16. calendar_label.pack()

  17. root.mainloop()
复制代码


注意,在这个例子里使用的是 `Label` 小部件而不是 `Button`,并且选择了一种等宽字体(Courier),这样可以确保每个字符的宽度相同,从而实现日历的对齐。

尝试运行代码,您会发现日历文本已经对齐显示。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-9-7 16:01:48 | 显示全部楼层    本楼为最佳答案   
这样~
  1. from tkinter import *
  2. import calendar
  3. root=Tk()
  4. b=Button(root,
  5.          text=calendar.month(2025,9),
  6.          foreground="navy",
  7.          background="bisque",
  8.          font="汉仪长艺体简 22 ",
  9.          relief="groove",
  10.          borderwidth=12,
  11.          justify=LEFT)
  12. b.pack()
  13. mainloop()
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-9-8 08:46:15 | 显示全部楼层
好有复古感觉
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-9-13 11:39:43 | 显示全部楼层
666
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-21 05:27

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表