[英]Why isn't this frame in tkinter centered correctly?
我希望这个输入栏和稍后我将添加到框架中的其他内容正确居中,我收到了这个应该可以工作的代码,但事实并非如此。
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()
如您所见,框架未居中,那么我该如何解决?
为了实现以全屏为中心的小部件,我不得不使用网格管理器。 下面的代码可以工作,但确切的定位需要对框架填充进行一些摆弄。 frame padx = w/2-300 和 pady = h/2-45 是通过反复试验找到的任意值。
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
会自动将大小更改为Frame
内对象的大小(当您使用pack()
时),但Frame
内没有任何内容。 您将所有小部件直接放在root
中 - 因此Frame
没有大小(宽度为零,高度为零)并且不可见。
当我使用tk.Frame(root, bg='red', width=100, height=100)
,我会在中心看到小红框。
你有两个问题:
(1)您将Entry
放在错误的父级中-它必须是frame
而不是root
,
(2) 您使用place()
,它不会将Frame
调整为其子级,并且它的大小为零 - 所以您看不到它。 您必须手动设置 Frame 的大小(即tk.Frame(..., width=100, height=100)
),或者您可以使用pack()
,它会自动调整大小。
我为背景添加了 colors 以查看小部件。 window 为blue
,框架为red
。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.