1

我希望这个输入栏和稍后我将添加到框架中的其他内容正确居中,我收到了这个应该可以工作的代码,但事实并非如此。

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()

如您所见,框架未居中,那么我该如何解决?

4

2 回答 2

0

Frame自动将大小更改为内部对象的大小Frame(当您使用时pack()),但您内部没有任何内容Frame。您将所有小部件直接放入root- 因此Frame没有大小(宽度为零,高度为零)并且不可见。

当我使用时,我tk.Frame(root, bg='red', width=100, height=100)会在中心看到小红框。

你有两个问题:

(1) 你Entry输入了错误的父母 - 它必须frame代替root,

(2) 您使用place()which 不会调整Frame其子项的大小并且它的大小为零 - 所以您看不到它。您必须手动设置 Frame 的大小(即tk.Frame(..., width=100, height=100)),或者您可以使用pack()它,它会自动调整大小。

我为背景添加颜色以查看小部件。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()

在此处输入图像描述

于 2021-04-02T12:34:43.427 回答
0

为了实现以全屏为中心的小部件,我不得不使用网格管理器。下面的代码可以工作,但确切的定位需要对框架填充进行一些摆弄。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()
于 2021-04-02T00:31:49.460 回答