2016-07-14 779 views
2

我使用tkinter创建项目,当我创建一个窗口时,似乎无法让窗口标题居中(与大多数程序一样)。下面是示例代码:Tkinter:如何居中窗口标题

from tkinter import * 

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

root.mainloop() 

有没有办法到中心窗口的标题呢?在此先感谢

回答

1

没有什么可以做的。 Tkinter无法控制窗口管理器或操作系统如何显示窗口标题,而不是指定文本。

0

我想出了做这项工作一招,它由在标题前简单地添加尽可能多的空白:

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

谢谢!但是,根据不同的显示器,结果会不一样吗? –

+1

这假定具有特定字体的固定大小的窗口。如果用户更改默认系统字体或调整窗口大小,标题将不再显示居中。 –

+0

好吧,告诉我一个情况,这不起作用。 –

0

更多地添加到Billal建议的是根据窗口大小调整的示例。我仍然不会推荐它,因为它只是视觉美学的黑客,但如果你真的想拥有它。

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

这只适用于非常特殊的情况。就我而言,它惨败了。这真的取决于如何配置os/window管理器。要做到这一点,您需要获取窗口管理器使用的字体,根据该字体计算标题字符串的实际宽度,计算空间的宽度,然后相应地进行调整。 –

+1

是的,我不希望它在大多数情况下工作,或者它需要更多的调整,我使用的是Windows 10.如上所述,如果OP真的需要它,我不会建议它就在那里。 –