简体   繁体   English

Python 3 tkinter:消息框上的focus_force

[英]Python 3 tkinter: focus_force on messagebox

I'm running python 3 code in background which should show a popup window in some situations.我在后台运行 python 3 代码,在某些情况下应该显示一个弹出窗口 window。 I'm using tkinter for this:我为此使用 tkinter :

import tkinter as tk
from tkinter import messagebox

def popup(message, title=None):
    root = tk.Tk()
    root.withdraw()
    root.wm_attributes("-topmost", 1)
    messagebox.showinfo(title, message, parent=root)
    root.destroy()

popup('foo')

The ok-button in this infobox should get the focus automatically when popping up.此信息框中的确定按钮应在弹出时自动获得焦点。 Sadly I'm not able to do this.可悲的是,我无法做到这一点。 I tried root.focus() , but it does not help.我试过root.focus() ,但它没有帮助。 Any ideas how to solve that?任何想法如何解决这个问题? TIA TIA

BTW: The code should be platform independent (Linux and Windows).顺便说一句:代码应该独立于平台(Linux 和 Windows)。

Edit: Maybe I missunderstood the focus keyword and I should clarify my question:编辑:也许我误解了焦点关键字,我应该澄清我的问题:

root = tk.Tk()
root.focus_force()
root.wait_window()

When calling the code above the root window is active, even if I worked in eg the browser before.当调用根 window 上方的代码时,即使我之前在浏览器中工作过也是如此。 Is this also possible for messagebox.showinfo ? messagebox.showinfo也可以这样做吗? Adding root.focus_force() in the popup function does not help.在弹出窗口 function 中添加root.focus_force()没有帮助。

Is this even possible?这甚至可能吗? Or is it necessary to create my own root window?或者是否有必要创建我自己的根 window? I really like the appearance of the messagebox with the icon.我真的很喜欢带有图标的消息框的外观。

Edit 2: Here is a video: https://filebin.net/no195o9rjy3qq5c4/focus.mp4 The editor is the active window, even after the popup was shown.编辑 2:这是一个视频: https://filebin.net/no195o9rjy3qq5c4/focus.mp4编辑器是活跃的 window,即使在显示弹出窗口之后也是如此。 In Linux I it works as expected.在 Linux I 中,它按预期工作。

You can use the default argument in the messagebox function.您可以使用messagebox function 中的default参数。

default constant默认常量

Which button to make default: ABORT, RETRY, IGNORE, OK, CANCEL, YES, or NO (the constants are defined in the tkMessageBox module).将哪个按钮设为默认:ABORT、RETRY、IGNORE、OK、CANCEL、YES 或 NO(常量在 tkMessageBox 模块中定义)。

So, here is an example to highlight the "ok" button.因此,这是一个突出显示“确定”按钮的示例。

import tkinter as tk
from tkinter import messagebox

def popup(message, title=None):
    root = tk.Tk()
    root.withdraw()
    messagebox.showinfo(title, message, parent=root, default = "ok")

    root.destroy()

popup('foo')

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM