我使用tkinter創建項目,當我創建一個窗口時,似乎無法讓窗口標題居中(與大多數程序一樣)。下面是示例代碼:Tkinter:如何居中窗口標題
from tkinter import *
root = Tk()
root.title("Window Title".center(110))# Doesn't seem to work
root.mainloop()
有沒有辦法到中心窗口的標題呢?在此先感謝
我使用tkinter創建項目,當我創建一個窗口時,似乎無法讓窗口標題居中(與大多數程序一樣)。下面是示例代碼:Tkinter:如何居中窗口標題
from tkinter import *
root = Tk()
root.title("Window Title".center(110))# Doesn't seem to work
root.mainloop()
有沒有辦法到中心窗口的標題呢?在此先感謝
沒有什麼可以做的。 Tkinter無法控制窗口管理器或操作系統如何顯示窗口標題,而不是指定文本。
我想出了做這項工作一招,它由在標題前簡單地添加儘可能多的空白:
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()
輸出:
另外,您可以使用由空格組成的字符串,並在乘法後將其連接到標題。我的意思是:
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()
更多地添加到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()
這隻適用於非常特殊的情況。就我而言,它慘敗了。這真的取決於如何配置os/window管理器。要做到這一點,您需要獲取窗口管理器使用的字體,根據該字體計算標題字符串的實際寬度,計算空間的寬度,然後相應地進行調整。 –
是的,我不希望它在大多數情況下工作,或者它需要更多的調整,我使用的是Windows 10.如上所述,如果OP真的需要它,我不會建議它就在那裏。 –
謝謝!但是,根據不同的顯示器,結果會不一樣嗎? –
這假定具有特定字體的固定大小的窗口。如果用戶更改默認系統字體或調整窗口大小,標題將不再顯示居中。 –
好吧,告訴我一個情況,這不起作用。 –