【问题标题】:Python tkinter - auto click on selected item from TreeviewPython tkinter - 自动单击 Treeview 中的选定项目
【发布时间】:2020-09-24 10:08:34
【问题描述】:

我有一个树形视图小部件,可以显示表格中的简单列表。
我想自动突出显示列表中的一项。 (这很好用)。
现在,我希望该项目自动接收鼠标单击(无需用户进行任何操作)。根据文档,使用命令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

【问题讨论】:

    标签: python html tkinter treeview bind


    【解决方案1】:

    这是一条有点不专业的路线,但是使用 py-game 之类的库可以自动单击或用鼠标选择,但您必须考虑屏幕分辨率。也可以试试看是否有属性可以自动选择,查看Tkinter参考指南寻求帮助,Link 1

    【讨论】:

      【解决方案2】:

      我找到解决办法

      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()
      

      【讨论】:

        【解决方案3】:

        为了自动化选择,我找到了这个解决方案:在插入数据来自数据库表的循环中,我使用 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)
        

        【讨论】:

          猜你喜欢
          • 2017-03-24
          • 2015-08-17
          • 2012-08-16
          • 1970-01-01
          • 2011-04-17
          • 2017-09-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多