簡體   English   中英

PySimpleGUI 列表框右鍵菜單

[英]PySimpleGUI Listbox right click menu

我想知道,是否可以使右鍵菜單在列表框中的選定框上起作用?

右鍵菜單示例

右鍵菜單示例

我已經成功地為整個列表框制作了一個右鍵菜單

layout = [
        [gui.Listbox(size=(35, 22), key='chat', values=messages,
                     right_click_menu=['&Right', ['Delete', 'Favourite', 'Reply', 'Copy', 'Edit']])],
        [gui.InputText(key='input', size=(25, 10)), gui.Button('Send', bind_return_key=True, size=(9, 1))]
    ]

但它並不完全是我想要的。 我想要:如果我右鍵單擊列表框中的一個框,該框將被選中,並且該菜單的操作將僅影響該框。 假設我右鍵單擊中間框並按刪除,中間框將被刪除。 我知道如何處理單擊菜單的事件,但到目前為止,我無法真正知道單擊了哪條消息。

這是可能的,但需要 tkinter 代碼和破解 PySimleGUI 代碼。 這里是按鈕 3 的新回調,但選擇最近的一個,而不是精確的那個。 也許sg.Tablesg.Tree可以實現更好的選擇。

import PySimpleGUI as sg

def RightClickMenuCallback(event, element):
    widget = element.Widget
    current = widget.curselection()
    if current:
        widget.selection_clear(current[0])
    index = widget.nearest(event.y)
    widget.selection_set(index)
    element.TKRightClickMenu.tk_popup(event.x_root, event.y_root, 0)
    element.TKRightClickMenu.grab_release()

messages = [
    'This is the start of your chat!',
    'demo messages',
    'dont know what to right',
]

command = ['Delete', 'Favourite', 'Reply', 'Copy', 'Edit']
layout = [
    [sg.Listbox(size=(35, 22), key='chat', values=messages,
        right_click_menu=['&Right', command])],
    [sg.InputText(key='input', size=(25, 10)),
     sg.Button('Send', bind_return_key=True, size=(9, 1))],
]
window = sg.Window("Test", layout, finalize=True)
chat = window['chat']
chat.Widget.bind('<Button-3>', lambda event,
    element=chat: RightClickMenuCallback(event, element))

while True:

    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    print(event, values)

window.close()

[編輯]

IMO,應首選圖書館提供的方式。

import PySimpleGUI as sg

messages = [
    'This is the start of your chat!',
    'demo messages',
    'dont know what to right',
]

command = ['Delete', 'Favourite', 'Reply', 'Copy', 'Edit']
cmd_layout = [[sg.Button(cmd, size=(10, 1))] for cmd in command]
layout = [
    [sg.Listbox(values=messages, size=(35, 22), key='chat'),
     sg.Column(cmd_layout)],
    [sg.InputText(key='input', size=(25, 10)),
     sg.Button('Send', bind_return_key=True, size=(9, 1))],
]
window = sg.Window("Test", layout, finalize=True)
window['input'].expand(expand_x=True)

while True:

    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    print(event, values)

window.close()

如果您需要在單擊鼠標按鈕 1 時生成事件,請將選項enable_events=True添加到sg.Listbox 當任何事件產生時,您可以通過values['chat']window['chat'].get()此列表框中當前選擇的項目列表,現在只有一個項目被選擇,所以消息是values['chat'][0]

如果需要索引,則必須調用window['chat'].get_indexes() ,它將當前選擇的項目作為索引列表返回。 因此,同樣,通過window['chat'].get_indexes()[0]獲取所選項目的索引

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM