How to specify where a Tkinter window opens?

后端 未结 5 1708
抹茶落季
抹茶落季 2020-12-02 12:54

How can I tell a Tkinter window where to open, based on screen dimensions? I would like it to open in the middle.

5条回答
  •  难免孤独
    2020-12-02 13:37

    If you would like the window to be centered.

    Then this type of a function may help you -:

    def center_window(size, window) :
        window_width = size[0] #Fetches the width you gave as arg. Alternatively window.winfo_width can be used if width is not to be fixed by you.
        window_height = size[1] #Fetches the height you gave as arg. Alternatively window.winfo_height can be used if height is not to be fixed by you.
        window_x = int((window.winfo_screenwidth() / 2) - (window_width / 2)) #Calculates the x for the window to be in the centre
        window_y = int((window.winfo_screenheight() / 2) - (window_height / 2)) #Calculates the y for the window to be in the centre
    
        window_geometry = str(window_width) + 'x' + str(window_height) + '+' + str(window_x) + '+' + str(window_y) #Creates a geometric string argument
        window.geometry(window_geometry) #Sets the geometry accordingly.
        return
    

    Here the window.winfo_screenwidth function is used for getting the width of the device screen. And the window.winfo_screenheight function is used for getting the height of the device screen.

    These can be called on a Tk window of python.

    Here you can call this function and pass a tuple with the (width, height) of the screen as the size.

    You can customize the calculation as much as you want and it will change accordingly.

提交回复
热议问题