4

In the code below, the first dialog box gets focus immediately, so the user can just type an answer and press enter. In the second one, that doesn't seem to happen when running in Windows. Running Raspbian 9, both windows get focus when they open.

Is there any way I can get both windows to get focus when they open in Windows?

import tkinter as tk
from tkinter import simpledialog

root = tk.Tk()
root.withdraw()

answer1 = simpledialog.askstring("Test1","This one gets focus when it opens",parent=root)
answer2 = simpledialog.askstring("Test2","This one doesn't",parent=root)
mgroat
  • 1,092
  • 1
  • 11
  • 16
  • Try adding `root.after(50, lambda: (root.deiconify(), root.withdraw()))` before showing second dialog. – acw1668 Dec 04 '19 at 10:01
  • Well it seems to be a windows thingy. Here is a solution from another thread that you might want to have a look at. https://stackoverflow.com/questions/22751100/tkinter-main-window-focus – Jason Chia Dec 09 '19 at 09:28

2 Answers2

6

I have watched this question for a few days now hoping someone might shed some light on this issue. I'm running Python 3.6.5 under windows 10 and get the same problem.

I have tried several different things but it seems Microsoft does things their own way. I have finally found a thing that works, but only if you don't hide the root window:

import tkinter as tk
from tkinter import simpledialog

root = tk.Tk()
#root.withdraw()     # This does not work if you hide the root window

root.update_idletasks()
answer1 = simpledialog.askstring("Test1","This one gets focus",parent=root)

root.update_idletasks()
answer2 = simpledialog.askstring("Test2","This one doesn't",parent=root)
figbeam
  • 7,001
  • 2
  • 12
  • 18
  • I wonder if the fucus issue is related to another one I answer here on this post: [Tkinter filedialog is stealing focus and not returning it without “Alt-tab” in Python 3.4.1](https://stackoverflow.com/questions/53763079/tkinter-filedialog-is-stealing-focus-and-not-returning-it-without-alt-tab-in-p/53765237#53765237) – Mike - SMT Dec 02 '19 at 21:40
  • @Mike-SMT Which solution would you think of? – Basj Dec 02 '19 at 21:51
  • @Basj the solution was the same as figbeam's. Using udate_idletasks(). – Mike - SMT Dec 02 '19 at 21:54
  • It does not work, see `root.withdraw() # This does not work if you hide the root window`. – Basj Dec 02 '19 at 21:55
  • @Basj I am aware. I was only speculating that it was related to another post and not saying I had a solution to this one. – Mike - SMT Dec 02 '19 at 22:07
0

I found the following worked (with a small flicker of the root window on destroy()):

root = tk.Tk()
root.withdraw()
filename = filedialog.askopenfilename()
root.deiconify()
root.destroy()