TheHoff TheHoff - 1 year ago 101
Python Question

Tkinter, show Calendar in Toplevel window on button click

I deleted my previous question about this in order to simplify my question and communicate the question clearer. I've got a project with multiple classes inside of it and I'd like to get a Calendar to display in a new window once I click a button. I am currently using this Calendar script with a minor change inside of my overall script. I changed Frame to Toplevel in the first part of the Calendar script like this:

class Calendar(tk.Toplevel):

def __init__(self, parent, **kw):

Toplevel.__init__(self, parent, **kw)

Now this does create the Calendar in a Toplevel window along with the rest of my script but it does it as soon as the program is started. I want to get it to show when it is called later on by the user.


class Application(tk.Tk): # tk.Tk creates main window

def __init__(self):

self.calendar = Calendar(self)

def create_options(self):
self.widgets = tk.Frame(self)
text = "...", command=self.show_Calendar
).place(x=525, y=130)

which would call this:

def show_Calendar(self):
'''shows calendar'''
toplevel = Toplevel(), y=0)

The button does create a window but there is nothing in it. What would be the best way to get this Calendar to only show in the window that appears when the button is clicked?

Answer Source
self.calendar = Calendar(self)

Putting this line within your application init will create it at the same time that the application is created. You would want to move this into your show_Calendar method.

def show_Calendar(self):
    '''shows calendar'''
    toplevel = Toplevel(), y=0)

toplevel = Toplevel() does not make any sense here. You are creating a blank Toplevel and making it a local variable. This Toplevel is not related to your Calendar in any way.

Within the Calendar script, you made sure that the Calendar class inherits from Toplevel, so any time you create a Calendar, it will be attached to its own Toplevel.

def show_Calendar(self):
    '''shows calendar'''
    self.calendar = Calendar(self)

I was looking at your previous question before you deleted it, and if you would also like to remove the calendar when the user changes focus, you should look into Events and Bindings here, specifically <FocusOut>.