Lidor
Lidor

Reputation: 11

how to make Tkinter windows appear when opened rather than start minimized?

How can I open Tkinter windows (such as entry, text...) and make them appear on the screen when they are opened rather than start minimized ? I don't really know how to start... I have some windows but they are opened minimized. I searched on the internet, but found nothing that may be relevant. how can I do it ? using python on windows (both Python 3 and Python 2) thanks for the help in advance !

EDIT: the problem now as I mentioned in a comment here is that I have to force the window to be showed. But when I do so, the window does not start centered even if I use a function to center it that worked before.

code:

def center(toplevel):
    toplevel.update_idletasks()
    w = toplevel.winfo_screenwidth()
    h = toplevel.winfo_screenheight()
    size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
    x = w/2 - size[0]/2
    y = h/2 - size[1]/2
    toplevel.geometry("%dx%d+%d+%d" % (size + (x, y)))


def paste_func():
    global text_box
    text_box.insert(END, top.clipboard_get())
    button_pressed()


def button_pressed(x=0):
    # This function determines which button was pressed, and closes this menu/message box/etc...
    global pressed
    pressed = x
    destroy_top()


def destroy_top():
    # This function closes this menu/message box/etc...
    global top
    top.iconify()
    top.withdraw()
    top.quit()

def get_text():
    global pressed
    global top
    global text_box

    pressed = 0
    top = Tk()
    top.withdraw()
    top.rowconfigure(0, weight=0)
    top.columnconfigure(0, weight=0)
    top.config(height=0, width=0)
    top.protocol('WM_DELETE_WINDOW', lambda: button_pressed(-1))

    text_box = Entry(top, width=50)
    text_box.focus_set()
    text_box.grid(row=0, column=0)
    but = Button(top, text='Enter', command=button_pressed)
    but.grid(row=0, column=1)
    paste = Button(top, text='Paste', command=paste_func)
    paste.grid(row=0, column=2)

    top.deiconify()
    text_box.focus_set()
    top.after(0, top.focus_force())
    center(top)
    top.mainloop()

    if pressed == -1:
        exit()

    return text_box.get('1.0', index2=END)

Upvotes: 0

Views: 1665

Answers (1)

Dan
Dan

Reputation: 4663

The window.focus_force() method does this:

Force the input focus to the widget. This is impolite. It's better to wait for the window manager to give you the focus. See also .grab_set_global() below.

Sometimes if this doesn't work, you can manually force it like so:

from Tkinter import *

window = Tk()
window.after(2000, window.focus_force)
window.mainloop()

Sometimes you will have issues on Macs which can require some additional finagling but this should work fine elsewhere (OP has not specified any information about environment).

Upvotes: 1

Related Questions