我正在构建一个下拉菜单,用于选择开始日期。它有3个级联,分别命名为年,月,日。生成一天级联的内容,以便可用天数与所选年份和月份一致。 在单个会话中,用户可能/可能会多次更改日期。Tkinter菜单选择日期
我的问题:当用户第一次选择年/月时,会生成days命令。此后,任何新年/月的组合,下面的代码只是将命令添加到级联。因此,这一天的级联包含两个月的日子。
我一直在努力使代码删除旧的菜单栏进入daymenu并重新创建它基于新的数据。 我想知道,如何对预先存在的运行菜单进行更改?我已经搜索了tkinter文档,但不知道如何实现它。
import calendar as cal
import Tkinter as tk
import datetime
import os.path
window = tk.Tk()
# Menu variables:
year = tk.IntVar()
month = tk.IntVar()
day = tk.IntVar()
hour = tk.IntVar()
minute = tk.IntVar()
dur_hour = tk.IntVar()
dur_minute = tk.IntVar()
duration = tk.StringVar()
start = tk.StringVar()
# list initializations
list_of_years = []
list_of_months = []
list_of_hours = []
list_of_days = []
list_of_minutes = []
def year_seter(value):
year.set(value)
all_for_day()
def all_for_day(): #checks if the data needed to determine number of days in the month is present
list_of_days = []
y = year.get()
m = month.get()
lenght_of_month = cal.monthrange(y,m)
lenght_of_month2 = lenght_of_month[1]
if m != 0 and y != 0:
make_daylist(lenght_of_month2)
make_daymenu()
def month_seter(value):
month.set(value)
all_for_day()
def day_seter(value):
day.set(value)
def time_parameters():
the_date = datetime.datetime(1,1,1,0,0,0,0)
the_date = the_date.now()
end_year = the_date.year
make_yearlist(1995, end_year)
make_monthlist()
make_hourlist()
make_minutelist()
def make_yearlist(the_year, end_year):
while the_year <= end_year:
list_of_years.append(the_year)
the_year += 1
def make_monthlist():
for i in range(12):
list_of_months.append(i + 1)
def make_daylist(num_days):
for i in range(num_days):
list_of_days.append(i + 1)
def make_hourlist():
for i in range(24):
list_of_hours.append(i)
def make_minutelist():
for i in range(60):
list_of_minutes.append(i)
def make_daymenu():
for the_day in list_of_days:
daymenu.add_command(label=the_day, command=lambda : day_seter(the_day))
window.config(menu=menubar)
# The following constructs the menu
time_parameters()
menubar = tk.Menu(window)
yearmenu = tk.Menu(menubar)
for the_year in list_of_years:
yearmenu.add_command(label=str(the_year), command=lambda the_year=the_year: year_seter(the_year))
menubar.add_cascade(label = 'Year', menu=yearmenu)
window.config(menu=menubar)
monthmenu = tk.Menu(menubar)
for the_month in list_of_months:
monthmenu.add_command(label=the_month, command=lambda the_month=the_month: month_seter(the_month))
menubar.add_cascade(label = 'Month', menu=monthmenu)
window.config(menu=menubar)
daymenu = tk.Menu(menubar)
menubar.add_cascade(label = 'Day', menu=daymenu)
window.config(menu=menubar)
window.mainloop()
当然,所有的月份至少有28天,所以你需要添加或删除更多的东西。 –
@ByanOakley:我不太清楚如何实施你的建议。这不像使用'daymenu.delete(29,31)'那么简单,因为那会重复1..28天。限制for循环只添加所需的日期需要找出菜单中已有的日期。如何做到这一点? – unutbu
我也曾想过这个解决方案,但我仍然在学习基础知识,所以我不知道如何实现它。无论如何,感谢你们两位的投入。 – Sasha