- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想知道如何安排 ttk 小部件(例如标签或按钮)上的文本自动调整大小。
更改文本的大小很容易,只需更改样式中的字体即可。然而,将它与窗口大小的变化 Hook 有点棘手。在网上我发现了一些提示,但没有发布完整的答案。
所以,下面是一个完整的工作示例,作为我自己问题的答案。我希望有人觉得它有用。如果有人有进一步的改进建议,我会很高兴看到他们!
最佳答案
下面的例子展示了两种技术,一种是通过重新调整窗口大小来激活(见 resize()
方法,绑定(bind)到 <Configure>
事件),另一种是直接改变字体大小(见 mutate()
方法) )。
其他需要调整大小的代码是 __init__()
中的网格配置代码。方法。
运行示例时,两种方法之间存在一些交互,但我认为在“真实”情况下,一种技术就足够了,因此不会出现该问题。
from tkinter import *
from tkinter.ttk import *
class ButtonApp(Frame):
"""Container for the buttons."""
def __init__(self, master=None):
"""Initialize the frame and its children."""
super().__init__(master)
self.createWidgets()
# configure the frame's resize behaviour
master.columnconfigure(0, weight=1)
master.rowconfigure(0, weight=1)
self.grid(sticky=(N,S,E,W))
# configure resize behaviour for the frame's children
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
# bind to window resize events
self.bind('<Configure>', self.resize)
def createWidgets(self):
"""Make the widgets."""
# this button mutates
self.mutantButton = Button(self, text='Press Me',
style='10.TButton')
self.mutantButton.grid(column=0, row=0, sticky=(N,S,E,W))
self.mutantButton['command'] = self.mutate
# an ordinary quit button for comparison
self.quitButton = Button(self, text='Quit', style='TButton')
self.quitButton.grid(column=0, row=1, sticky=(N,S,E,W))
self.quitButton['command'] = self.quit
def mutate(self):
"""Rotate through the styles by hitting the button."""
style = int(self.mutantButton['style'].split('.')[0])
newStyle = style + 5
if newStyle > 50: newStyle = 10
print('Choosing font '+str(newStyle))
self.mutantButton['style'] = fontStyle[newStyle]
# resize the frame
# get the current geometries
currentGeometry = self._root().geometry()
w, h, x, y = self.parseGeometry(currentGeometry)
reqWidth = self.mutantButton.winfo_reqwidth()
reqHeight = self.mutantButton.winfo_reqheight()
# note assume height of quit button is constant at 20.
w = max([w, reqWidth])
h = 20 + reqHeight
self._root().geometry('%dx%d+%d+%d' % (w, h, x, y))
def parseGeometry(self, geometry):
"""Geometry parser.
Returns the geometry as a (w, h, x, y) tuple."""
# get w
xsplit = geometry.split('x')
w = int(xsplit[0])
rest = xsplit[1]
# get h, x, y
plussplit = rest.split('+')
h = int(plussplit[0])
x = int(plussplit[1])
y = int(plussplit[2])
return w, h, x, y
def resize(self, event):
"""Method bound to the <Configure> event for resizing."""
# get geometry info from the root window.
wm, hm = self._root().winfo_width(), self._root().winfo_height()
# choose a font height to match
# note subtract 30 for the button we are NOT scaling.
# note we assume optimal font height is 1/2 widget height.
fontHeight = (hm - 20) // 2
print('Resizing to font '+str(fontHeight))
# calculate the best font to use (use int rounding)
bestStyle = fontStyle[10] # use min size as the fallback
if fontHeight < 10: pass # the min size
elif fontHeight >= 50: # the max size
bestStyle = fontStyle[50]
else: # everything in between
bestFitFont = (fontHeight // 5) * 5
bestStyle = fontStyle[bestFitFont]
# set the style on the button
self.mutantButton['style'] = bestStyle
root = Tk()
root.title('Alice in Pythonland')
# make a dictionary of sized font styles in the range of interest.
fontStyle = {}
for font in range(10, 51, 5):
styleName = str(font)+'.TButton'
fontName = ' '.join(['helvetica', str(font), 'bold'])
fontStyle[font] = styleName
Style().configure(styleName, font=fontName)
# run the app
app = ButtonApp(master=root)
app.mainloop()
root.destroy()
关于button - Python3 : How to dynamically resize button text in tkinter/ttk?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12018540/
我正在使用的 tkinter 版本正在访问 tk.TclVersion=8.6。 我可以从 ttk.Style() 访问 stylename='TSpinbox'。 Stylename = TSpin
是否可以配置具有透明背景的 tkinter 或 ttk 小部件(Label、Entry、Text)以便放置它们在具有自定义背景颜色的容器中或在 Canvas 图形或图像之上? 我也在寻找一种方法来更改
我需要为按钮小部件创建一个自定义样式,它与使用 ttk 'clam' 主题的按钮具有相同的外观。 我可以这样设置主题: s = ttk.Style() s.theme_use('clam') 但是,鉴
最近开始使用 ttk 来改善我的 GUI 外观,但我在编辑 ttk.OptionMenu 样式时遇到了困难。正如我所理解的,下面的代码应该改变所有单选按钮和选项菜单的背景。对于 Radiobutton
除了已记录的类之外,ttk.Spinbox 类和 tk.Spinbox 类之间有什么区别? 我发现了一些差异,例如: ttk.Spinbox 在按下箭头后设置为 0,而 tk.Spinbox 则不会。
我正在使用主要使用 C 和 C++ 构建的遗留(桌面风格,现在已知)Windows 应用程序。当此应用程序在触摸屏 Windows 笔记本电脑上运行时,我需要在用户点击对话框屏幕上的输入框时自动显示触
我在使用 ttk.Notebook 和 grid 布局管理器布局两个相同的 ttk.Treeview 小部件时遇到问题。当我仅使用一个 TreeView (放置在标签框架中、放置在框架(部分)中、放置
有人可以解释一下为什么entry.select_range()适用于Button,但不适用于ttk.Button吗? from tkinter import * from tkinter import
考虑这个简单的代码: from tkinter import * from tkinter.ttk import * root= Tk() ttk.Label(root, text='Heading
我正在尝试在我的程序中加入可自定义的主题选择。我一直在引用这个指南:http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-themes.html
考虑这个简单的代码: from Tkinter import * import ttk root= Tk() ttk.Label(root, text='Heading Here').grid(row
当我更改图像的前景色时,包含位图图像的 ttk 标签无法正常工作。只有 ttk 标签有这个问题。 Tkinter 标签正常工作。 代码如下: import tkinter as tk import t
我有一排包含 ttk.Combobox 的小部件,当我勾选该行末尾的复选框时,我想更改该行中小部件的背景颜色。对于 tkinter,只需使用配置就很简单,但是对于 ttk,您必须使用一个主题,该主题似
这是我的代码 from Tkinter import * import ttk, tkMessageBox import os font = ("Avenir", 24) b = ttk.Style(
我想制作一个简单的弹出消息,当鼠标进入选项时显示以图标表示的选项名称,并在鼠标离开时隐藏。 这些图标是按钮内的图像,我已经能够在使用菜单小部件输入按钮时显示消息,但是当鼠标离开按钮时,它不会取消发布,
import tkinter from tkinter import ttk def main(): root = tkinter.Tk() numpad = NumPad(root)
我正在尝试使用这个问题 (Tk treeview column sort) 的答案中说明的 ttk.Treeview 排序函数,它适用于像“abc”、“bcd”、“cde”等字符串,但是当我尝试对数字
我有一个处于“禁用”状态的 ttk 条目。禁用时输入字段的背景颜色为浅蓝色。我怎样才能将它更改为默认的灰色?从这篇文章中,我了解了如何更改前景色。 tkinter ttk Entry widget -
使用ttk标签,可以指定根据标签状态显示的多个图像。但我无法让它发挥作用。这是代码。 from tkinter import * from tkinter.ttk import * BITMAP0 =
Python ttk gui 的创建很容易,并且大部分具有原生的外观和感觉 (win7)。不过,我遇到了一个小问题: 我想要一个看起来像 ttk.LabelFrame 但没有标签的框架。仅仅省略文本选
我是一名优秀的程序员,十分优秀!