2021年1月2日星期六

Nested function in Toplevel window

I set up a Toplevel window under a root window to allow a user to select a date after an api call. The root window selects a station name and station id. A toplevel window is created to select a date. I can print the date value to the terminal, but I can't use the date in subsequent functions. I want the user selected date (start_date) to be converted to datetime, then add 24 hours to create an end_date. These values will be converted to unixtime for another data call for the time period(end_date - start_date). It seems something is wrong with the grab_date and/or grab_level functions. However, the program must be stopped manually, also instead of executing and then stoping.

from tkinter import *  from tkcalendar import *  from datetime import datetime, timedelta    root = Tk()  root.geometry('450x200')      def station_id_window():      """ Returns corresponding station id based on station name      selected and pastes the value to the open window. """      for key in list(stn_dic.keys()):          if key == clicked.get():              x = stn_dic.get(key)              mylabel = Label(root, text=x).grid(row=2, column=1, pady=5)      def stationid():      """ Returns corresponding station id based on station name      selected and allows the value to be used throughout the program. """      for key in list(stn_dic.keys()):          if key == clicked.get():              x = stn_dic.get(key)              return x      def grab_date():      """ Grabs the user selected start date from the calendar. """      root.withdraw()      top = Toplevel()      top.title('Calendar to Select Start Data')      top.iconbitmap('Drive.ico')      top.geometry('400x400')        def grab_label():          """ Print date from calendar in window. """          mylabel2.config(text=cal.get_date())          x = cal.get_date()          print(x)        # create a calendar and capture variable      cal_value = StringVar()      cal = Calendar(top, selectmode='day', year=2020, month=10, day=1,                     date_pattern='mm/dd/y', textvariable=cal_value)      cal.grid(row=0, column=0)        mylabel2 = Label(top, text='', font=('Helvetica', 14))      mylabel2.grid(row=1, column=1)        # Create button and label to capture start date      btn3 = Button(top, text='Select Start Date:', command=grab_label)      btn3.grid(row=1, column=0)        return grab_label      def start_date():      """ Converts the captured start date to a datetime value. """      date_str = grab_date()      date = datetime.strptime(date_str, '%m/%d/%Y')      print(date)      def end_date():      """ Add 24 hours to the previously captured start date. """      date2 = start_date() + timedelta(hours=24)      return date2      api = {'stations':  [{'station_name': 'AAAA', 'station_id': '123'},                       {'station_name': 'BBBB', 'station_id': '456'}                       ]         }    # create two lists  stn_name = []  stn_id = []    for record in api['stations']:      stn_name.append(record['station_name'])      stn_id.append(record['station_id'])    # combine lists to create a dictionary with subsequent (key: value) pairs  stn_dic = dict(zip(stn_name, stn_id))    # Obtain user input  clicked = StringVar()  clicked.set(stn_name[0])    # Create various buttons, labels, and menus used in the window 1  mylabel = Label(root, text='Select Station:', font=('Helvetica', 14))  mylabel.grid(row=0, column=0, pady=10)    drop = OptionMenu(root, clicked, *stn_name)  drop.grid(row=0, column=1, pady=5)    mybutton = Button(root, text='Click to Identify Station ID:',                    command=station_id_window)  mybutton.grid(row=2, column=0, pady=5)    btn2 = Button(root, text='After Selections: Click Here to Continue',                font=('Helvetica', 14), command=grab_date)  btn2.grid(row=4, column=0, columnspan=2, pady=20)    root.mainloop()    
https://stackoverflow.com/questions/65542684/nested-function-in-toplevel-window January 03, 2021 at 02:34AM

没有评论:

发表评论