1
votes

I'm running python 3 code in background which should show a popup window in some situations. I'm using tkinter for this:

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. Any ideas how to solve that? TIA

BTW: The code should be platform independent (Linux and 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 e.g. the browser before. Is this also possible for messagebox.showinfo? Adding root.focus_force() in the popup function does not help.

Is this even possible? Or is it necessary to create my own root 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. In Linux I it works as expected.

1
Read up on Dialog Windows - stovfl
Are you using MacOs or Windows? I am using windows, and the button is already in focus when the window opens up. If you are using Mac, then see my answer. - 10 Rep
Why would you expect anything done to root to have any effect on the messagebox? Those are two separate windows. - jasonharper

1 Answers

0
votes

You can use the default argument in the messagebox function.

default constant

Which button to make default: ABORT, RETRY, IGNORE, OK, CANCEL, YES, or NO (the constants are defined in the tkMessageBox module).

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!