|
| 1 | +from datetime import time |
| 2 | + |
| 3 | +import flet as ft |
| 4 | + |
| 5 | + |
| 6 | +def main(page: ft.Page): |
| 7 | + page.horizontal_alignment = ft.CrossAxisAlignment.CENTER |
| 8 | + |
| 9 | + def get_system_hour_format(): |
| 10 | + """Returns the current system's hour format.""" |
| 11 | + return "24h" if page.media.always_use_24_hour_format else "12h" |
| 12 | + |
| 13 | + def format_time(value: time) -> str: |
| 14 | + """Returns a formatted time string based on TimePicker and system settings.""" |
| 15 | + use_24h = time_picker.hour_format == ft.TimePickerHourFormat.H24 or ( |
| 16 | + time_picker.hour_format == ft.TimePickerHourFormat.SYSTEM |
| 17 | + and page.media.always_use_24_hour_format |
| 18 | + ) |
| 19 | + return value.strftime("%H:%M" if use_24h else "%I:%M %p") |
| 20 | + |
| 21 | + def handle_change(e: ft.Event[ft.TimePicker]): |
| 22 | + selection.value = f"Selection: {format_time(time_picker.value)}" |
| 23 | + |
| 24 | + time_picker = ft.TimePicker( |
| 25 | + value=time(hour=19, minute=30), |
| 26 | + help_text="Choose your meeting time", |
| 27 | + on_change=handle_change, |
| 28 | + ) |
| 29 | + |
| 30 | + def open_picker(e: ft.Event[ft.Button]): |
| 31 | + choice = format_dropdown.value |
| 32 | + hour_format_map = { |
| 33 | + "system": ft.TimePickerHourFormat.SYSTEM, |
| 34 | + "12h": ft.TimePickerHourFormat.H12, |
| 35 | + "24h": ft.TimePickerHourFormat.H24, |
| 36 | + } |
| 37 | + time_picker.hour_format = hour_format_map[choice] |
| 38 | + page.show_dialog(time_picker) |
| 39 | + |
| 40 | + page.add( |
| 41 | + ft.Row( |
| 42 | + alignment=ft.MainAxisAlignment.CENTER, |
| 43 | + controls=[ |
| 44 | + format_dropdown := ft.Dropdown( |
| 45 | + label="Hour format", |
| 46 | + value="system", |
| 47 | + width=260, |
| 48 | + key="dd", |
| 49 | + options=[ |
| 50 | + ft.DropdownOption( |
| 51 | + key="system", |
| 52 | + text=f"System default ({get_system_hour_format()})", |
| 53 | + ), |
| 54 | + ft.DropdownOption(key="12h", text="12-hour clock"), |
| 55 | + ft.DropdownOption(key="24h", text="24-hour clock"), |
| 56 | + ], |
| 57 | + ), |
| 58 | + ft.Button( |
| 59 | + "Open TimePicker", |
| 60 | + icon=ft.Icons.SCHEDULE, |
| 61 | + on_click=open_picker, |
| 62 | + ), |
| 63 | + ], |
| 64 | + ), |
| 65 | + selection := ft.Text(weight=ft.FontWeight.BOLD), |
| 66 | + ) |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + ft.run(main) |
0 commit comments