我一直在尝试弄清楚如何制作一个可以触发其他窗口小部件更新的窗口小部件。在此示例中,更改Month_Display小部件中的月/年必须更新Input_Table小部件中的标签集。红色背景的日子代表周末。
我不知道该怎么做。如何在类外调用make_month()函数或如何触发Month_Display小部件重新加载月份?
这是我的示例代码:
from tkinter import *
import calendar
import datetime
class App(Frame):
def __init__(self, master=None, **kwargs):
Frame.__init__(self, master)
self.grid()
# Widget
self.input_table = Input_Table(self, self, borderwidth = 3, relief = RIDGE)
self.month = Month_Display(self, self, borderwidth = 3, relief = RIDGE)
# Frame positioning
self.input_table.grid(row=0, column=0)
self.month.grid(row=0, column=2, sticky = NE)
def run(self):
self.mainloop()
class Input_Table(Frame):
def __init__(self, parent, *args, **kwargs):
Frame.__init__(self, *args, **kwargs)
self.labels = {}
self.world_month = datetime.datetime.now().month
self.world_year = datetime.datetime.now().year
self.world_day = datetime.datetime.now().day
self.make_month()
# Show dates on the left side of the table
# Piece of code that I want to trigger whenever button is pressed
def make_month(self):
date = datetime.datetime(year = self.world_year, month = self.world_month, day=self.world_day)
the_day = datetime.datetime.weekday(date)
for day in range(1, calendar.monthrange(self.world_year, self.world_month)[1] + 1):
if (the_day) == 5 or (the_day) == 6:
self.labels[day] = Label(self, text=day, bg="red")
else:
self.labels[day] = Label(self, text=day)
self.labels[day].grid(row=day, column=0)
date += datetime.timedelta(days = 1)
the_day = datetime.datetime.weekday(date)
class Month_Display(Frame):
def __init__(self, parent, the_date, *args, **kwargs):
Frame.__init__(self, *args, **kwargs)
self.selected_month = IntVar()
self.selected_month.set(datetime.datetime.now().month)
self.selected_year = IntVar()
self.selected_year.set(datetime.datetime.now().year)
# Widgets
# These two buttons have to trigger the make_month()
self.button_left = Button(self, text="<<", command=lambda: self.update_month(-1))
self.button_left.grid(row=1, column = 0)
self.button_right = Button(self, text=">>", command=lambda: self.update_month(1))
self.button_right.grid(row=1, column = 4)
self.month_label = Entry(self, textvariable=self.selected_month, width=3)
self.month_label.grid(row=1, column = 1)
self.slash = Label(self, text="/")
self.slash.grid(row=1, column = 2)
self.year_label = Entry(self, textvariable=self.selected_year, width=5)
self.year_label.grid(row=1, column = 3)
# Updating month and year
def update_month(self, offstet):
self.selected_month.set(self.selected_month.get() + offstet)
if self.selected_month.get() > 12:
self.selected_year.set(self.selected_year.get() + offstet)
self.selected_month.set(1)
elif self.selected_month.get() < 1:
self.selected_year.set(self.selected_year.get() + offstet)
self.selected_month.set(12)
app = App()
app.run()
回答这样的问题将使我对如何使小部件相互通信有一个深刻的认识。