tkinter simpledialog giving focus to parent of window it was called from when submitted

624 Views Asked by At

I am attempting to open window2 from window1 and asking for a string in between. On a successful (or unsuccessful) input, window1, seems to take focus back from window2. Even if focus_set is called on window2 after the dialogue is closed.

window2 takes focus on creation if he askstring is omitted

import os
import tkinter as tk
from tkinter import ttk
from tkinter import simpledialog

class window2:
    def __init__(self,root):
        self.root = root
        self.root.withdraw()
        simpledialog.askstring("askstring","askstring")
        self.root.deiconify()

class window1:
    def __init__(self,root):
        self.root = root
        self.button = tk.Button(self.root,text = "Test", command = self.newwindow)
        self.button.grid()
    
    def newwindow(self):
        newin = window2(tk.Toplevel(self.root))

if __name__ == "__main__":
    toproot = tk.Tk()
    win = window1(toproot)
    win.root.mainloop()

I'm wondering if it is doing this because of the way I've setup the classes or simply if its something simpledialogue does which triggers this effect.

1

There are 1 best solutions below

0
On

After noticing my simplified code was missing the withdraw() and the deiconify() I figured I could bring the window back to front once the window was visible again.


import tkinter as tk
from tkinter import ttk
from tkinter import simpledialog

class window2:
    def __init__(self,root:tk.Tk):
        self.root = root
        self.root.withdraw()
        simpledialog.askstring("this","sucks",parent = self.root)
        self.root.deiconify()
        self.root.wait_visibility()
        self.root.lift()
class window1:
    def __init__(self,root):
        self.root = root
        self.button = tk.Button(self.root,text = "Test", command = self.newwindow)
        self.button.grid()
    
    def newwindow(self):
        newin = window2(tk.Toplevel(self.root))

if __name__ == "__main__":
    toproot = tk.Tk()
    win = window1(toproot)
    win.root.mainloop()

Not exactly elegant, but it works.