In Tkinter how do i remove focus from a widget?

后端 未结 6 899
余生分开走
余生分开走 2021-02-08 13:37

I\'d like to remove focus from a widget manually.

相关标签:
6条回答
  • 2021-02-08 14:08

    If you use ttk widgets you can "remove" the focus ring by removing the color; for example on a button:

    style = ttk.Style()
    style.configure('TButton', focuscolor='')
    
    0 讨论(0)
  • 2021-02-08 14:12

    If the dummy widget is Canvas then c.focus() will not work.

    use c.focus_set() or c.tk.call('focus',c) to first focus on the canvas window itself.


    That's because

    c.focus()

    ... returns the id for the item that currently has the focus, or an empty string if no item has the focus. Reference

    c.focus(id_) will focus on the item having id id_ within the canvas.

    c.focus("") will remove the focus from any item in the canvas.


    Hence (within some callback)

    c.config(highlightthickness = 0) # to remove the highlight border on focus
    c.foucs_set()
    c.focus("") # just to be sure
    

    The reason c.focus() functions differently is that within Tcl/Tk's Commands there's the "Primary" Command focus

    as well as the Canvas-specific Widget Command focus

    That's not an issue within the Tcl/Tk syntax but in the tkinter module c.focus() will call the underlying canvas-specific foucs.

    From tkinter.py within the Canvas class Line 2549

    def focus(self, *args):
            """Set focus to the first item specified in ARGS."""
            return self.tk.call((self._w, 'focus') + args)
    
    0 讨论(0)
  • 2021-02-08 14:15

    You can focus to another dummy widget.

    Edit

    from Tkinter import *
    
    def callback():
        print master.focus()
    
    master = Tk()
    e = Entry(master)
    e.pack()
    e.focus()
    b = Button(master, text="get", width=10, command=callback)
    b.pack()
    
    master.mainloop()
    

    Focusing on a non-'focusable' widget will remove focus from another widget.

    0 讨论(0)
  • 2021-02-08 14:20

    My solution is root.focus() it will remove widget focus.

    0 讨论(0)
  • 2021-02-08 14:25
    • Set focus to another widget to remove focus from the target widget is a good idea. There are two methods for this: w.focus_set() and w.focus_force(). However, method w.focus_force() is impolite. It's better to wait for the window manager to give you the focus. Setting focus to parent widget or to the root window removes focus from the target widget.
    • Some widgets have takefocus option. Set takefocus to 0 to take your widget out of focus traversal (when user hits <Tab> key).
    0 讨论(0)
  • 2021-02-08 14:32

    So the question may be a duplicate here, but the answer from @Bryan Oakley works perfectly for me in Python 3.8

    root.focus_set()
    

    Too easy...

    0 讨论(0)
提交回复
热议问题