Python tkinter自动单击树视图中的选定项

2024-10-03 13:21:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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é

如何在没有用户干预的情况下激活鼠标单击? 谢谢你抽出时间,祝你愉快

Auto Selection Item


Tags: eventgetloaddelalistvaluesprint
3条回答

为了自动化选择,我找到了这个解决方案:在insert for循环中,数据来自数据库的表,我使用1个特定的db数据作为值(最好是唯一的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)

这是一个稍微非专业的路线,但使用诸如py game之类的库可以自动单击或用鼠标选择,但您必须考虑屏幕分辨率。您还可以尝试查看是否有可自动选择的属性,请查看Tkinter参考指南以获取帮助,Link 1

我找到了解决办法

import tkinter as tk
import tkinter.ttk as ttk
import time

tree = ttk.Treeview()
for i in range(10):
    iid = tree.insert('', 'end', text=i)
tree.pack()

def event_test(iid):
    t['text'] = iid
    print("iid", iid)

def move_bottom():
    iid = tree.get_children('')[-1]
    time.sleep(1)
    if iid != tree.focus():
        iid = tree.get_children('')[5]
        tree.focus(iid)
        tree.selection_set(iid)
        print("iid", iid)

        tree.event_add('<<Declenche>>', '<ButtonRelease-1>')
        tree.after(1000, lambda: tree.event_generate('<<Declenche>>'))
        tree.bind('<<Declenche>>', event_test(iid))

t = tk.Label()
t.pack()
tk.Button(text='move', command=move_bottom).pack()

tree.mainloop()

相关问题 更多 >