[英]How do I make a pop-up window with choices in python?
對於我正在處理的項目,我想制作一個彈出窗口 window 有幾個不同的選項,可以根據用戶選擇的選項返回一個值; 我找到了獲得簡單彈出窗口的解決方案,但沒有找到返回值的解決方案。 我正在使用 Python 3.8。
正如 barny 所建議的,PySimpleGUI 非常簡單。
您所描述的是 PySimpleGUI Cookbook 中所謂的一次性 window 。
這些類型的 GUI 可以編寫為一行 PySimpleGUI 代碼,因為您不需要完整的事件循環。
import PySimpleGUI as sg
event, values = sg.Window('Choose an option', [[sg.Text('Select one->'), sg.Listbox(['Option a', 'Option b', 'Option c'], size=(20, 3), key='LB')],
[sg.Button('Ok'), sg.Button('Cancel')]]).read(close=True)
if event == 'Ok':
sg.popup(f'You chose {values["LB"][0]}')
else:
sg.popup_cancel('User aborted')
在通過鏈式read
調用調用 Window 之后,您將獲得用於關閉 window(哪個按鈕或如果使用“X”關閉)和值字典的事件。 在這種情況下,您的 values 字典將有一個項目values['LB']
。 對於列表框,此值將是一個列表。 要選擇項目,您可以參考values['LB'][0]
為簡單起見,PySimpleGui 是通往 go 的方法 - 它似乎適用於 Windows 10 上的 Python 3.8.3。
創建一個簡單的 gui 對話框來進行選擇沒有比這更容易的了(盡管它也可以在需要時做更復雜的 UI):
import PySimpleGUI as sg
#sg.theme('DarkAmber') # Add a touch of color
options = ['Option a','Option b','Option c']
# All the stuff inside your window.
layout = [
[sg.Text('Select one->'), sg.Listbox(options,select_mode=sg.LISTBOX_SELECT_MODE_SINGLE,size=(20,len(options)))],
[sg.Button('Ok'), sg.Button('Cancel')]
]
# Create the Window
window = sg.Window('Make your choice', layout)
# Event Loop to process "events" and get the "values" of the input
while True:
event, values = window.read()
print( f"event={event}" )
if event is None or event == 'Ok' or event == 'Cancel': # if user closes window or clicks cancel
break
# close the window
window.close()
if event == "Cancel":
print( "You cancelled" )
else:
print('You entered ', values[0])
sg.popup( f"You selected {values[0]}" )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.