为什么tkinter按钮的高度选项在OSX和Windows上表现不同?
我有一段代码,其中有以下这一行:
self.button = Button(frame, text="CALCOLA", width=28, height=2, command=callback)
当我在OSX系统上运行这段代码时,按钮显示为单行,但它与其他控件之间上下都有间隔。而在Windows系统上,按钮的高度是两行,所以它上下都紧贴着其他项目,就像图片所示。
有没有办法让两个系统的效果一样?此外,我还注意到按钮的宽度在两个系统下也不完全相同,能不能让宽度的表现也一致呢?
1 个回答
Tk的控件本来是要有一种“原生的外观和感觉”,虽然现在看起来有点过时。所以它们看起来不同是故意的。如果你想让不同平台上的界面看起来相似,一个选择是使用画布,不过这需要很多工作。我建议你专注于让它在两个平台上看起来都不错,而不是完全一样。
不过,控件的宽度是根据字符而不是像素来计算的。大概估计一下,两个系统大约都能容纳28个字符(OSX的边距似乎稍微大一点)。所以字体很重要。
确保默认的字体和字体大小完全相同。
import Tkinter
import tkFont
root = Tk()
tkFont.nametofont("TkDefaultFont").actual()
我的Windows 7系统的设置是: {'family': 'Segoe UI', 'weight': 'normal', 'slant': 'roman', 'overstrike': 0, 'underline': 0, 'size': 9}
我的Windows Server 2008系统的设置是: {'family': 'Tahoma', 'weight': 'normal', 'slant': 'roman', 'overstrike': 0, 'underline': 0, 'size': 8}
还有更多的默认字体,比如:“TkTextFont”。
如果你使用相同的字体,界面看起来会更相似。
前面两个“CALCOLA”按钮是在我的Windows 7系统上。第一个是使用默认系统设置,第二个是使用以下设置:
root.option_add("*Button.Font", "Tahoma 8 bold roman normal underline")
Tkinter.Button(root, text="CALCOLA").pack()
第三个“CALCOLA”按钮是来自我的Windows 2008 Server系统,使用的是默认设置。你也可以改变背景颜色:
root.option_add("*Button.Background", "white")
Tkinter.Button(root, text="CALCOLA").pack()
你还可以为所有新元素更改背景:
root.option_add("*Background", "blue")
Tkinter.Button(root, text="CALCOLA").pack()
Tkinter.Label(root, text="CALCOLA").pack()
更新:
控件的宽度和高度都是基于字体的,文本和边缘之间的间距则是根据操作系统的主题来决定的。不过你可以配置更多的设置,比如按钮的:
'highlightThickness' 'text' 'image' 'compound' 'height' 'borderWidth' 'padY' 'padX' 'font' 'activeForeground' 'activeBackground' 'underline' 'width' 'state' 'highlightColor' 'textVariable' 'overRelief' 'takeFocus' '-borderwidth' 'foreground' '-background' 'repeatInterval' 'repeatDelay' 'background' '-foreground' 'bitmap' 'highlightBackground' 'disabledForeground' 'wrapLength' 'default' 'cursor' 'command' 'relief' 'anchor' 'justify'
将padY和padX设置为相似的值也有助于让两个操作系统的外观更相似。你可以这样获取当前的设置:
print(
root.option_get("padY", "Button"),
root.option_get("padX", "Button"),
)