Tkinter:如何将窗口标题居中显示

3
我正在使用tkinter创建一个项目,当我创建窗口时,似乎无法使窗口标题居中(就像大多数现代程序一样)。以下是示例代码:
from tkinter import *

root = Tk()
root.title("Window Title".center(110))# Doesn't seem to work

root.mainloop()

有没有一种方法可以将窗口标题居中显示?谢谢。
5个回答

3

你无法做任何事情。Tkinter无法控制窗口管理器或操作系统如何显示窗口的标题,只能指定文本。


1
我想到了一个解决办法,就是在标题前面添加尽可能多的空格。这样做可以达到预期效果。
import tkinter as tk

root = tk.Tk()
root.title("                                                                          Window Title")# Add the blank space
frame = tk.Frame(root, width=800, height=200, bg='yellow')
frame.grid(row=0,column=0)

root.mainloop()

输出:

enter image description here

另外,你可以使用一个由空格组成的字符串,并在乘法之后将其连接到标题中。我的意思是:

import tkinter as tk

root = tk.Tk()
blank_space =" " # One empty space
root.title(80*blank_space+"Window Title")# Easier to add the blank space 
frame = tk.Frame(root, width=800, height=200, bg='yellow')
frame.grid(row=0,column=0)

root.mainloop()

谢谢!但是这不会因为不同的显示器而产生不同的结果吗? - Hung Truong
1
这假设一个固定大小的窗口和特定字体。如果用户更改默认系统字体或调整窗口大小,则标题将不再居中显示。 - Bryan Oakley
告诉我一个这种情况不适用的例子。 - Billal Begueradj
你应该使用几个 "\t",而不是其他字符。 - user8598233

1
更进一步补充Billal的建议,这是一个根据窗口大小调整的示例。尽管它只是视觉美学的hack,但如果你真的想要它,我仍然不建议使用它。
import tkinter as tk

def center(e):
    w = int(root.winfo_width() / 3.5) # get root width and scale it ( in pixels )
    s = 'Hello Word'.rjust(w//2)
    root.title(s)

root = tk.Tk()
root.bind("<Configure>", center) # called when window resized
root.mainloop()

2
这只在非常特定的情况下才有效。在我的情况下,它失败了。这实际上取决于操作系统/窗口管理器的配置方式。要做到正确,您需要获取窗口管理器使用的字体,根据该字体计算标题字符串的实际宽度,计算空格的宽度,然后进行相应的调整。 - Bryan Oakley
1
是的,我不指望它在大多数情况下都能工作,或者需要更多的调整,我正在使用Windows 10。正如所述,这不是我建议的东西,只是如果OP真的想要它,那就在那里。 - Steven Summers

0

只需在开头添加一个句号或任何特殊字符,以便考虑空格,然后再添加空格。

title='UNI-CARD'root.title(f'. {title}')


0
width=root.winfo_screenwidth()
spacer=(" "*(int(width)//6))
root.title(spacer+"Your title")

这不是非常完美,但这可以工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接