positioncustomtkinterdpi-aware

How to center a CustomTkinter App on the screen?


The way I get it, scaling is dpi aware in customtkinter, but positioning is not? It seems I need to set x_pos and y_pos regarding x+<x_pos>+<y_pos> in physical pixels (retrieved with e.g. ctypes). But I would really like to know the conversion that ctk does when being set to scale dpi aware (default). I tried: dpi_scaling = self.tk.call('tk', 'scaling')

But this gave me a value of 1.33.. something instead of 1.25, with my display being set to 125%.

So is there a way to get the actual conversion factor? Or is there a more straightforward way to center the app on the screen?

Best Regards


Solution

  • Your solution doesn't work because tkinter does not support scaling and you are calling a tkinter function and not a customtkinter.

    To get the scaling used by customtkinter you can use something like this:

    import customtkinter as ctk
    
    win = ctk.CTk()
    
    scaling = ctk.ScalingTracker().get_window_scaling(win)
    print(scaling)
    
    win.mainloop()
    

    To center your window you can do this:

    import customtkinter as ctk
    
    
    win = ctk.CTk()
    
    scaling = ctk.ScalingTracker().get_window_scaling(win)
    width = win.winfo_screenwidth()
    height = win.winfo_screenheight()
    
    win.geometry(f"300x300+{int(width/2*scaling)}+{int(height/2*scaling)}")
    
    win.mainloop()
    

    This will center the top left corner of the window in the middle of the screen.

    Hope I helped you, have a nice day