Tkinter主窗口焦点

2024-04-28 22:14:11 发布

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

我有以下代码

window = Tk()
window.lift()
window.attributes("-topmost", True)

这段代码的工作原理是它比所有其他窗口都显示我的Tkinter窗口,但它仍然只能解决一半的问题。虽然该窗口实际上显示在所有其他窗口之上,但该窗口没有焦点。有没有一种方法不仅可以使窗口成为Tkinter最前面的窗口,而且可以将焦点放在它上面?


Tags: 方法代码truetkinterwindowattributestk焦点
3条回答

如果focus_force()不工作,可以尝试执行:

window.after(1, lambda: window.focus_force())

基本上是一样的,只是写得不同。我刚刚在Python2.7上测试过。

root.focus_force()不起作用,但上面的方法起作用了。

Windows的解决方案有点棘手——你不能仅仅从另一个窗口窃取焦点,你应该以某种方式将你的应用程序移到前台。 但首先,我建议你消耗一个littlebit of windows theory,所以我们可以确认,这是我们想要达到的。

正如我在comment中提到的,这是一个使用SetForegroundWindow函数的好机会(还可以检查限制!)。但考虑到这些东西是一个廉价的黑客,因为用户“拥有”前台,Windows会不惜一切代价阻止你:

An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user.

另外,请检查this页上的备注:

The system automatically enables calls to SetForegroundWindow if the user presses the ALT key or takes some action that causes the system itself to change the foreground window (for example, clicking a background window).

下面是一个最简单的解决方案,因为我们能够模拟Alt按:

import tkinter as tk
import ctypes

#   store some stuff for win api interaction
set_to_foreground = ctypes.windll.user32.SetForegroundWindow
keybd_event = ctypes.windll.user32.keybd_event

alt_key = 0x12
extended_key = 0x0001
key_up = 0x0002


def steal_focus():
    keybd_event(alt_key, 0, extended_key | 0, 0)
    set_to_foreground(window.winfo_id())
    keybd_event(alt_key, 0, extended_key | key_up, 0)

    entry.focus_set()


window = tk.Tk()

entry = tk.Entry(window)
entry.pack()

#   after 2 seconds focus will be stolen
window.after(2000, steal_focus)

window.mainloop()

一些链接和示例:

不知道你面临什么问题。但下面是对我非常有用的示例代码。

from tkinter import *

window = Tk()

def handle_focus(event):
    if event.widget == window:
        window.focus_set()
        input1.focus_set()


label1 = Label(window,text = "Enter Text 2")
input1 = Entry(window, bd=5)

label2 = Label(window,text = "Enter Text 2")
input2 = Entry(window, bd=5)

submit = Button(window, text="Submit")

label1.pack()
input1.pack()
label2.pack()
input2.pack()
submit.pack(side=BOTTOM)

window.lift()
window.attributes("-topmost", True)

window.bind("<FocusIn>", handle_focus)

hwnd = window.winfo_id()

window.mainloop()

这是在Windows10上使用最新的Python3.6测试的。

Test Results

结果是在运行程序之后,我可以开始输入,然后他输入到第一个文本框

相关问题 更多 >