首页 > 解决方案 > Python tkinter - 自动单击 Treeview 中的选定项目

问题描述

我有一个树视图小部件,它显示表格中的简单列表。
我想自动突出显示列表中的一项。(这很好用)。
现在,我希望该项目自动接收鼠标单击(无需用户进行任何操作)。根据文档,使用命令 Rec_list.event_generate ('<ButtonRelease-1>' .format (button-1), when = "now") 但没有结果。

# coding:utf-8
#version 3.x python

from tkinter import *
from tkinter.ttk import *
from tkinter import ttk

def Load_Recette_Contenu():

    Load_Recette = tk.Toplevel()
    Load_Recette.title("Ouvrit une recette SAF")
    Load_Recette.geometry("325x178+0+0")
    Load_Recette.resizable(width=False, height=False)                                            
    # Fenêtre verrouillée
    Load_Recette.attributes("-toolwindow", 1)                                                         
    # Supprime les boutons Réduire/Agrandir
    Load_Recette.attributes("-topmost", 1)                                                             
    # au premier plan


# ==================================================
#                              TreeView
# ==================================================


# --- Insertion Table Nom HV dans TreeView
def DisplayData():
    for i in Recette_DB_BackEnd.loadRecord():
        # print("Nom de la recette --> ", i[0])
        Rec_list.insert('', 'end', text=i[0], values=(i[0]))

# --- Insertion Scrollbar
scrollbar_y = Scrollbar(Recette_TreView, orient='vertical')                                 # Ascenseur Vertical
scrollbar_y.place(x=299, y=0, height=169)


Rec_list = ttk.Treeview(Recette_TreView, selectmode="browse", columns=(1), show="headings", yscrollcommand=scrollbar_y.set) 
# --- En-tête
Rec_list.heading('#1', text="Recettes")
# --- Largeur Colonnes
Rec_list.column('#1', width=300, minwidth=40, stretch=OFF)
Rec_list.place(x=0, y=0, width=301, height=168)

scrollbar_y.config(command=Rec_list.yview)                                                       # Ascenseur Vertical

DisplayData()



def selectionItem(a):
    # === [Sélection - Widget Treeview] ===


    curItem = Rec_list.focus()
    Liste = Rec_list.item(curItem)["values"]
    # print("winfo_name()", Rec_list.winfo_name())                                            # ID widget Treeview -- Exemple : winfo_name() !treeview
    # print("Liste - TreeView - Recette sélectionnée", Liste)                                 # Affiche la sélection contenu de la liste
    # print("Liste - TreeView - Colonne Nom -->", Liste[0])
    # for child in Rec_list.get_children():                                                            # Listing du contenu de la Treeview -- Exemple : ['Recette_2020.05_8_30.5_NoName']
    #     print(Rec_list.item(child)["values"])
    # print("Rec_list.item(curItem)[","values","][0]          ", Rec_list.item(curItem)["values"][0])                                   # Affiche Nom recette depuis Treeview -- Exemple : Recette_2020.05_8_30.5_NoName
    # print("Rec_list.get_children()", Rec_list.get_children())                                                                                       # iid -- Renvoie un tuple des valeurs iid des enfants de l'élément spécifié par l'argument élément. S'il est omis, vous obtenez un tuple contenant les valeurs iid des éléments de niveau supérieur.  --- exemple : Rec_list.get_children() ('I001', 'I002', 'I003', 'I004')
    # print("Rec_list.get_children()[0]", Rec_list.get_children()[0])

    # print("Rec_list.get_children()", Rec_list.get_children([Rec_list.item(curItem)["values"][0]]))   ????????????????????

    z = -1
    for child in Rec_list.get_children():
        z = z +1
        time.sleep(1)
        Rec_list.update()
        Rec_list.selection_set(Rec_list.get_children()[z])
        # Rec_list.event_generate('<ButtonRelease-1>'.format(button-1), when="now")
        Rec_list.focus_force()
        Rec_list.focus_set()
        Rec_list.focus(Rec_list.get_children()[z])
        Rec_list.update()

    # -- Identifie le type de bouton activé --
    # un bouton pressé(event.type = 4)
    # un bouton relaché(event.type = 5)
    # un bouton pressé en mouvement(event.type = 6)
    print("\ntype :", a.type)
    # -- Identifie quel bouton pressé --
    # clic gauche(Bouton 1): event.num = 1
    # clic droit(Bouton 3): event.num = 3
    print("num :", a.num)
    # Load_Recette.update()
    # Rec_list.event_generate('<ButtonPress-1>')
    # Load_Recette.update()


# ==================================================
#                              Evénement Treeview
# ==================================================
# via souris
Rec_list.bind('<ButtonRelease-1>', selectionItem)                                         # Le bouton de la souris a été relâché

如何在没有用户干预的情况下激活鼠标点击?谢谢你的时间,祝你有美好的一天

自动选择项目

标签: pythonhtmltkintertreeviewbind

解决方案


为了自动化选择,我找到了这个解决方案:在插入数据来自数据库表的循环中,我使用 1 个特定的 db-data 作为值(最好是唯一的 id)。我使用循环索引通过 get_children 方法获取 iid。在 for 我将数据插入到字典中,其中键是 iid,值是 db 中的值(唯一数据)。

如果目标是更改行中的数据并将其发送回数据库,您可以进行查询选择以找到第一个未更改的行,并仅选择唯一 id,该行的唯一数据(或使用主自动递增 rowid) . 使用该 id 获得该行的 iid,而不是使用该 iid 进行焦点和选择。在将该选择绑定到一个事件之后,您可以运行该调用事件来运行您的方法,而无需单击任何行。

def calling(event):
    selectedRow = tree.item(tree.focus())
    datas = selectedRow['values']
    var1 = datas[0]
    var2 = datas[1]

    yourMethod(var1, var2)


def keyGetter(val, lib):
    for key, value in lib.items():
         if val == value:
             return key
    return "key doesn't exist"

index = 0   
iidLibrary = dict()
for row in rows:
    tree.insert("", index, values = (row[0], row[1], row[2))
    iid = tree.get_children()[index]
    iidLibrary[iid] = row[3]

curs.execute(
"SELECT id_of_row FROM table WHERE something=? ORDER BY rowid ASC LIMIT 1", (variable, )
firstUnclosed = curs.fetchall()

iidActual = keyGetter(firstUnclosed[0][0], iidLibrary)
                
tree.focus(iidActual)
tree.selection_set(iidActual)

tree.bind('<<TreeviewSelect>>', calling)

推荐阅读