1

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.

Lugino
  • 21
  • 6
  • Read up on [Dialog Windows](http://effbot.org/tkinterbook/tkinter-dialog-windows.htm) – stovfl Jun 17 '20 at 20:14
  • 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 Jun 18 '20 at 01:10
  • Read [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/a/48045508/7414759) and [When to use the Toplevel Widget](http://effbot.org/tkinterbook/toplevel.htm) – stovfl Jun 18 '20 at 10:08
  • Why would you expect anything done to `root` to have any effect on the messagebox? Those are two separate windows. – jasonharper Jun 18 '20 at 14:10

1 Answers1

0

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!

Community
  • 1
  • 1
10 Rep
  • 2,217
  • 7
  • 19
  • 33