如何在ttk.Treeview中将焦点设置为特定的孩子,类似于点击它?

时间:2014-05-23 22:35:04

标签: python-3.x treeview focus ttk

我有一个包含许多条目小部件和树视图小部件的应用程序。我想要做的是让用户在树视图中选择一行(子),从子项中提取某些数据并显示在不同的条目小部件中。用户可以更改或保留所需的任何数据,点击“返回”按钮。在每个条目小部件上直到最后。点击'返回'在最后一个条目窗口小部件上应该将焦点重新放回Treeview,特别是列表中的下一个子节点(紧接在最初单击的行下面的行/子节点。

def display_chosen(self, event):#Called when user clicks row/child in 'dirdisplay' Treeview widget
        clickedfile = self.dirdisplay.focus()#Get child (row) id of click
        self.nextID = self.dirdisplay.next(clickedfile)#Get next child, place in class-wide accessible variable
        self.enableentries()#Enable entry boxes so data extraction to entry widgets work
        #Do whatever to send data to entry widgets

def enableentries(self):#Sets three entry widgets a, b, c to state normal.
    try:
        self.a.config(state=NORMAL)
        self.b.config(state=NORMAL)
        self.c.config(state=NORMAL)
    except AttributeError:
        pass   
def a_to_b(self, event):#While in entry 'a', hitting 'Return' calls this and sets focus to next entry widget, 'b'
    #Do whatever with data in a
    self.b.focus_set()

def b_to_c(self, event):#While in entry 'b', hitting 'Return' calls this and sets focus to next entry widget, 'c'
    #Do whatever with data in b
    self.c.focus_set()

def c_to_nex(self, event):#Hitting 'Return' on 'c' calls this, setting focus back to 'dirdisplay' treeview, giving focus to child immediately below what was originally clicked.
    #Do whatever with data in c
    print('Focus acknowledged')
    print(self.nextID)#Feedback to show me the nextID actually exists when I hit 'Return'
    self.dirdisplay.focus_set()
    self.dirdisplay.focus(self.nextID)

所以,这与我的其余代码一起(巨大的,我想我在这里展示了所有重要的内容,请告诉我是否需要更多代码)部分工作。 a_to_b,b_to_c正常工作。当调用c_to_nex时(我知道当我因为反馈打印而点击返回时调用它)我知道nextID是正确的,因为它确实打印了正确的子ID,但没有其他事情发生。我知道treeview具有焦点,因为在键盘上按下或向下遍历行。我也知道nextID描述的行是'排序'因为当我击中时,第三行(在nextID行下面)会突出显示。

这种''专注于nextID行并没有帮助我,因为我需要选择行,就好像用户点击了他或她自己。

This

描述了一段时间回答的类似问题,不幸的是,这些答案都没有帮助。我知道我已经离我很近了,我知道我可能正在使用&self.dirdisplay.focus(self.nextID)'错误或缺少选项。

谢谢!

1 个答案:

答案 0 :(得分:2)

经过多次尝试,我终于成功了解了它!

使用self.dirdisplay作为ttk.Treeview小部件......

def c_to_nex(self, event):#Hitting 'Return' on 'c' calls this, setting focus back to 'dirdisplay' treeview, giving focus to child immediately below what was originally clicked.
    #Do whatever with data in c
    print('Focus acknowledged')
    print(self.nextID)#Feedback to show me the nextID actually exists when I hit 'Return'
    self.dirdisplay.focus_set()
    self.dirdisplay.selection_set((self.nextID, self.nextID))
    self.dirdisplay.focus(self.nextID)

您需要上面的三重奏,就像您以编程方式将焦点设置到Treeview中的特定子/行一样 - 就像用户自己点击它一样。

self.dirdisplay.focus_set()给出Treeview小部件输入焦点,以便按向上/向下键正常工作。

self.dirdisplay.selection_set((self.nextID,self.nextID))为您提供实际突出显示的行的效果。 self.nextID重复,因为selection_set似乎需要一个与单行/子ID相对应的项目列表(根据文档)。

最后,self.dirdisplay.focus(self.nextID)似乎实际上是行焦点(你绑定的任何函数<>将激活)。

相关问题