如何为 Tkinter 小部件设置焦点?

编程入门 行业动态 更新时间:2024-10-26 15:29:29
本文介绍了如何为 Tkinter 小部件设置焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个简单的 Python + Tkinter 应用程序,显示 10 个项目的列表:

I have a simple Python + Tkinter application that displays a list of 10 items:

import Tkinter, ttk
list = ttk.Treeview( Tkinter.Tk() )
list.pack( fill = Tkinter.BOTH, expand = 1 )
items = [ list.insert( '', 'end', text = str( i ) ) for i in range( 10 ) ]
list.selection_set( items[ 0 ] )
list.focus_set() # This is not working - list has no focus :(
Tkinter.mainloop()

是否可以修改它,以便在应用程序启动后,列表将具有焦点并且我可以通过向上和向下箭头移动选择?应用程序启动后,应用程序的窗口具有焦点,但我无法用箭头移动选择,直到我用鼠标单击列表:(.我尝试了 focus_set()focus_force(),但它不起作用.

Is it possible to modify it so after application starts, list will have focus and i can move selection via up and down arrows? After app starts, app's window has focus, but i can't move selection with arrows until i click list with mouse :(. I tried different combinations of focus_set() and focus_force(), but it's not working.

在 Windows 7、OSX 10.7 和 Ubuntu 12.04 上使用 Python 2.7 检查

Checked with Python 2.7 on Windows 7, OSX 10.7 and Ubuntu 12.04

更新

如果将Treeview"更改为其他小部件,例如更改为Button",则焦点有效.因此,我似乎以某种方式错误地为 Treeview 设置了焦点.

If "Treeview" is changed to some other widget, for example to "Button", the focus is working. So it's seems that i set focus for Treeview somehow incorrectly.

推荐答案

终于找到了解决方案 - 似乎 Treeview 小部件需要设置两次焦点:第一次为小部件本身,第二次对于一个项目:

Found a solution at last - seems that Treeview widget need to be set focus two times: first for the widget itself, and second for an item:

list.selection_set( items[ 0 ] )
list.focus_set()
list.focus( items[ 0 ] ) # this fixes a problem.

这篇关于如何为 Tkinter 小部件设置焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 07:37:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1391330.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:何为   部件   焦点   Tkinter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!