简体   繁体   中英

Why isn't this frame in tkinter centered correctly?

I want this entry bar and other contents I'll add to the frame later to be centred correctly, I received this code that supposedly should work but it isn't.

import tkinter as tk
import math
import time

root = tk.Tk()
root.geometry()
root.attributes("-fullscreen", True)

exit_button = tk.Button(root, text = "Exit", command = root.destroy)
exit_button.place(x=1506, y=0)

frame = tk.Frame(root)
main_entry = tk.Entry(root, width = 100, fg = "black")
main_entry.place(x=50, y=50)
frame.place(relx=.5,rely=.5, anchor='center')

root.mainloop()

As you can see the frame isn't centred so how can I fix this?

In order to achieve widget centering on a fullscreen I've had to use grid manager. The code below works but the exact positioning requires some fiddling with frame padding. frame padx = w/2-300 and pady = h/2-45 are arbitrary values found using a bit of trial and error.

    import tkinter as tk

    root = tk.Tk()
    root.attributes( '-fullscreen', True )
    w, h = root.winfo_screenwidth(), root.winfo_screenheight()

    frame = tk.Frame( root )
    main_entry = tk.Entry( frame, width = 100 )
    main_entry.grid( row = 0, column = 0, sticky = tk.NSEW )
    frame.grid( row = 0, column = 0, padx = w/2-300, pady = h/2-45,  sticky = tk.NSEW )
    exit_button = tk.Button( frame, text = 'Exit', command = root.destroy )
    exit_button.grid( row = 1, column = 0, sticky = tk.NSEW )

    tk.mainloop()

Frame automatically changes size to size of objects inside Frame (when you use pack() ) but you have nothing inside Frame . You put all widgets directly in root - so Frame has no size (width zero, height zero) and it is not visible.

When I use tk.Frame(root, bg='red', width=100, height=100) then I see small red frame in the center.

You have two problems:

(1) you put Entry in wrong parent - it has to be frame instead of root ,

(2) you use place() which doesn't resize Frame to its children and it has size zero - so you don't see it. You would have to set size of Frame manully (ie. tk.Frame(..., width=100, height=100) ) or you could use pack() and it will resize it automatically.

I add colors for backgrounds to see widgets. blue for window and red for frame.

import tkinter as tk

root = tk.Tk()
root['bg'] = 'blue'

root.attributes("-fullscreen", True)

exit_button = tk.Button(root, text="Exit", command=root.destroy)
exit_button.place(x=1506, y=0)

frame = tk.Frame(root, bg='red')
frame.place(relx=.5, rely=.5, anchor='center')

main_entry = tk.Entry(frame, width=100, fg="black")
main_entry.pack(padx=50, pady=50)  # with external margins 50

root.mainloop()

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM