Home > Net >  Tkinter Make My Pop Up Window in Middle of the Screen
Tkinter Make My Pop Up Window in Middle of the Screen

Time:08-01

I am trying to make my Tkinter pop up window show up in the middle of the screen. I've seen this page and also this video. However, I have been unable to accomplish this. The video is actually a demontration to get the application to show up in the middle of the screen (which I have working). I thought I'd just be able to change the variables to apply the same idea to my pop up window, but I'm doing something wrong. My code is as follows (learned from the video):

from tkinter import *   
#this portion works, makes the application show up in the middle of the screen
window = Tk()
window_width = 500
window_height = 500
windowDim = str(window_width)   'x'   str(window_height)
window.geometry(windowDim)
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
xcord = (screen_width / 2) - (window_width / 2)
ycord = (screen_height / 2) - (window_height / 2)
window.geometry(f'{window_width}x{window_height} {int(xcord)} {int(ycord)}')

#this pop up window does not show up in the middle of the application
def pop():
    top = Toplevel(window)
    top_width = 200
    top_height = 200
    topDim = str(top_width)   'x'   str(top_height)
    top.geometry(topDim)
    top.title("Hi")
    movex = (window_width / 2) - (top_width / 2)
    movey = (window_height / 2) - (top_height / 2)
    top.geometry(f'{top_width}x{top_height} {int(movex)} {int(movey)}')
    popLabel = Label(top, text = "Ok")
    popLabel.place(relx = 0.5,rely=0.5,anchor = 'center')

I am trying to get everything in the middle. Application shows up in the middle of the screen, the pop up window shows up in the middle of the application, and the label shows up in the middle of the pop up window. Everything should be both vertically and horizontally centered.

CodePudding user response:

Your main code is perfect as the video in this link suggests. Now the problem with the popup window is that you are calculating the center of the popup window from the width of the window and not the width of the screen (since you said that you want everything on the center of the screen).

If your screen is 1600x900 then, your main window(500x500) will start at 1050x700.

For the pop up you are doing this,

movex=(500/2) - (200/2) = 250 - 100 = 100

movey=(500/2) - (200/2) = 250 - 100 = 100

final geometry = (200x200) 100 100

(this will be towards the top left corner of screen)

But it should be like this

final geometry = (200x200) (xcord 100) (ycord 100)

For any subsequent windows within this window, the adjustment should be added to the previous windows top-left coordinates.

  • Related