简体   繁体   中英

How can I get Calendar Button's value using its key inside the while loop, PySimpleGUI?

I am very new to PySimpleGUI. I am building a GUI for a desktop application and wanted to use a calendar. But there came a problem with retrieving the value of Calendar Button events in the while loop without timeouts in window.read() when I chose from Calendar Picker Popup. I tried to get its value using event == 'CalendarButton's text' , but couldn't, though its button text changes every time if you choose to set a different date. Can you please help with that, or how can I get its (or any element's) value using its key inside the while loop. Or at least can I use Tkinter calendar package. If so, how can I connect Tkinter Calendar with PySimpleGUI window, will I have to use an element's key bindings with Tkinter?

Here's my code for Calendar Button definition which I put into my window's layout:

sg.CalendarButton('Calendar', target='_CALENDAR_', pad=None, font=('MS Sans Serif', 10, 'bold'), 
                button_color=('red', 'white'), key='_CALENDAR_', format=('%d %B, %Y'))

and here's the while loop events handling part

# LOOP EVENTS #
while True:

    # READ EVENT VALUES #
    event, values = window.read()

    # EXIT OR CLOSE EVENT #
    if event is None or event == 'Exit':
        break

    # BUTTON EVENTS

    # CALENDAR BUTTON CLICKED EVENT #
    if event == 'Calendar':
        window['_CALENDAR_'](disabled=True)


# CLOSE WINDOW
window.close()

# POPUP
sg.Popup('Title',
        'The results of the window.',
        'The button clicked was "{}"'.format(event),
        'The values are', values)

Also, I cannot see this event's value in the sg.Popup() output after I exit the window

'EDITED' Sorry, there were errors in sg.Popup() . Now fixed it.

The way to both save the value and get the event is to create a hidden input field. Enable events for the input field and you'll get an event when the calendar fills in the input field that you set as the target.

import PySimpleGUI as sg

layout = [  [sg.Text('Calendar example')],
            [sg.In(key='-CAL-', enable_events=True, visible=False), sg.CalendarButton('Calendar', target='-CAL-', pad=None, font=('MS Sans Serif', 10, 'bold'),
                button_color=('red', 'white'), key='_CALENDAR_', format=('%d %B, %Y'))],
            [sg.Exit()]]

window = sg.Window('Calendar', layout)

while True:             # Event Loop
    event, values = window.read()
    print(event, values)
    if event in (None, 'Exit'):
        break
window.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM