Python:如何在tkinter wind中居中标记

2024-04-28 08:32:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图构建一个弹出窗口,其中包含不同的文本消息供用户响应。

我想办法把文本(标签)和按钮放在窗口中间,但没有成功。

Popup window

弹出窗口的大小已确定。框架内部居中应考虑文本标签的宽度和高度(以字母数量定义)。

正如您在代码中看到的,wh定义窗口大小,xbiasybias有一个表达式将testframe居中(两者都包含alpha1alpha2作为文本大小的校正因子)

我正在寻找alpha1alpha2(现在等于1)的数学表达式。。。或者更好的方法来构造这样一个弹出窗口。

root = Tk()
w = '400'
h = '100'
root.geometry('{}x{}'.format(w, h))
root.configure(bg='lightgreen')

txt = StringVar()
txt.set("This is an error message")

alpha1 = 1
alpha2 = 1
xbias = int(w) / 2 - (len(txt.get()) / 2) * alpha1
ybias = int(h) / 2 - alpha2

testframe = ttk.Frame(root)
testframe.grid(row=0, column=1, pady=ybias, padx=xbias)

label1 = ttk.Label(testframe, textvariable=txt)
label1.grid(row=0, column=0)

Tags: 文本txt定义表达式root标签gridint
2条回答

您是否考虑过为此使用.pack()方法。这样可以更容易地达到预期效果:

from tkinter import *

root = Tk()
top = Toplevel(root)

w = '400'
h = '100'
top.geometry('{}x{}'.format(w, h))

frame = Frame(top)

label = Label(frame, text="This is an error message")
button = Button(frame, text="Ok")

frame.pack(expand=True) #expand assigns additional space to the frame if the parent is expanded
label.pack()
button.pack()

root.mainloop()

经过一些研究,使用网格做这件事比预期的要容易得多,如下所示:

from tkinter import *

root = Tk()

w = '400'
h = '100'
root.geometry('{}x{}'.format(w, h))

label = Label(root, text="text")
label.grid(column=0, row=0)
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

root.mainloop()

如果我们分配.rowconfigure().columnconfigure()一个weight而不是0,那么指定的行和列将展开以填充窗口中给它的空间。

在根窗口中居中框架的方法如下:

Part A) Create A window with a specific size h, w (since it is a popup - in this example I disable resizing it ). Inside the frame- a Label and a Button:

root = Tk()
w = '200'
h = '80'
root.geometry('{}x{}'.format(w, h))
root.configure(bg='lightgreen')    ###To diff between root & Frame
root.resizable(False, False)

txt = StringVar()
txt.set("This is an error message")

testframe = ttk.Frame(root)
testframe.grid(row=0, column=1)

label1 = ttk.Label(testframe, textvariable=txt)
label1.grid(row=0, column=0, pady=10)

ok_button = ttk.Button(testframe, text="OK", command=root.destroy)
ok_button.grid()

Part B) In order to get frame's dimensions ( including Label and Button inside ) we use testframe.update() and then testframe.winfo_width()testframe.winfo_height() to obtain frame's updated values. xbias and ybias calculates the center to place the frame in the middle:

testframe.update()

xbias = int(w) / 2 - testframe.winfo_width() / 2
ybias = int(h) / 2- testframe.winfo_height() / 2
testframe.grid(row=0, column=1, pady=ybias, padx=xbias)

root.mainloop()

相关问题 更多 >