删除/创建函数中的小部件tkinter,python 3.8

问题描述

我尝试在tkinter中练习并加深我的理解。因此,我想创建一个简单的日历,以便用户可以看到当日的日期,并通过按下“下一个/上一个”按钮来相应地查看下一个/上一个月。

代码是:

import calendar
from tkinter import *
from datetime import datetime

def ShowCalendar(year,month):
    RowGrid=2
    ColGrid = calendar.monthrange(year,month)[0]+1
    ButtonsFrame = frame(root)
    ButtonsFrame.grid()
    for day in range(1,calendar.monthrange(year,month)[1]+1):
        b = Button(text=day,padx=paddingx,pady=6).grid(row=RowGrid,column=ColGrid)
        ColGrid += 1
        if ColGrid == 7:
            ColGrid=0
            RowGrid+=1

def NextMonth():
    global month
    global year

    month += 1
    if month == 13:
        month = 1; 
        year +=1
    MonthYear = MonthStr[month]+"   "+str(year)
    date.set(MonthYear)
    ShowCalendar(year,month)

def PrevMonth():
    global month
    global year

    month -= 1
    if month == 0:
        month = 12; 
        year -=1
    MonthYear = MonthStr[month]+"   "+str(year)
    date.set(MonthYear)
    ShowCalendar(year,month)

WeekDay = "Sun Mon Tue Wed Thu Fri Sat".split()
paddingx = 7
MonthStr = "Zero January February march April May June July August September October November     December".split()
year = datetime.Now().year
month = datetime.Now().month
calendar.setfirstweekday(calendar.SUNDAY)

root = Tk()
date = StringVar()
MonthYear = MonthStr[month]+"   "+str(year)
date.set(MonthYear)
root.title("Personal Calendar")

Label(root,textvariable=date).grid(columnspan=10,ipadx=70)
PrevButton = Button(root,text="<",command=PrevMonth,pady=6).grid(row=0,column=1)
NextButton = Button(root,text=">",command=NextMonth,column=5)

for num,day in enumerate(WeekDay):
    WD = Label(root,text=day,pady=6).grid(row=1,column=num)

ShowCalendar(year,month)
root.mainloop()

我有两个问题:

  1. 我希望按下一步/上一步按钮时将删除日按钮(1-31),以便正确显示月份。现在,它只是在前几天打印日期,因此用户看不到更改。
  2. 这导致我遇到下一个问题-我尝试创建一个包含日按钮的框架,因此我销毁了小部件,但是当我创建框架时,它给我一个错误“ TypeError:'Frame'object is不可通话”。
  3. 即使我尝试在NextMonth函数中使用b.destroy(),也是如此:
def NextMonth():
    global month
    global year

    month += 1
    if month == 13:
        month = 1; 
        year +=1
    MonthYear = MonthStr[month]+"   "+str(year)
    date.set(MonthYear)
    b.destry()
    ShowCalendar(year,month)

我收到错误消息:“ NameError:未定义名称'b'”

所以我认为我误解了使用tkinter传递给函数的参数,而且我不知道如何删除按钮,以便可以重新打印它们

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)