【问题标题】:How to justify text in a Button in Python ttk如何在 Python ttk 中的 Button 中对齐文本
【发布时间】:2019-02-18 05:23:04
【问题描述】:

我正在尝试在按钮中对齐(对齐)文本,比如说向左。 我找到了一些有用的代码here,基于我在下面创建的代码来检查标签的行为。

import tkinter as tk
import tkinter.ttk as ttk


app = tk.Tk()
style = ttk.Style()
style.layout(
        'Left1.TButton',[
            ('Button.button', None),
            ('Button.focus', {'children': [                
                ('Button.padding', {'children': [
                    ('Button.label', {'side' : 'left'}
                     )]}
                 )]}
             )]
        )

print("TButton.label->justify: ", style.lookup('TButton.label', 'justify'))
print("TButton.label->side: ", style.lookup('TButton.label', 'side'))

style.configure('TButton.label', justify='left')
style.configure('TButton.label', side='left')

print("TButton.label->justify: ", style.lookup('TButton.label', 'justify'))
print("TButton.label->side: ", style.lookup('TButton.label', 'side'))


ttk.Button(text="TButton", width=100, style="TButton").pack()
ttk.Button(text="Lef1.TButton", width=100, style="Left1.TButton").pack()

print("TButton.label options:\n", style.element_options('TButton.label'))

问题是对标签没有影响。它停留在按钮的中心。 更有趣的是最后一行。 输出是:

TButton.label options:
 ('compound', 'space', 'text', 'font', 'foreground', 'underline', 'width', 'anchor', 'justify', 'wraplength', 'embossed', 'image', 'stipple', 'background')

但如果我尝试设置“锚点”,我会遇到异常。我知道 ttk 中没有此功能,但为什么会出现在这里?

【问题讨论】:

  • 这可能是特定于平台的事情。你在什么平台上运行?例如,我知道在 OSX 上,有些事情是底层原生按钮根本不允许的。
  • Windows 10 但我在 Linux (Kali) 上进行了检查,但它也无法正常工作。
  • Anchor 没有为我抛出异常,尽管也没有改变任何东西。你的系统是什么?
  • 忘记补充说我使用的是 Python 3.6.4。您使用的是来自 ttk 的 Button 吗?我认为来自标准 Tkinter 的确实具有锚属性。您可以在创建按钮时使用它。

标签: python tkinter ttk


【解决方案1】:

我一直在使用以下样式并且它正在工作 - 这会将 anchor='center' 配置应用于我的所有按钮,但您可以为每个按钮创建自己的样式,只需将 'TButton' 更改为 '{插入您的样式名称}.TButton'(更多关于 https://www.pythontutorial.net/tkinter/ttk-style/ - 学习 ttk 样式的低估资源)。

不管怎样,代码如下:

style = ttk.Style()
style.theme_create( "button-center", parent="alt", settings={
        "TButton": {"configure": {"anchor": "center"}}} )

# Now just create the button itself

style.theme_use("button-center")
btn = ttk.Button({the_frame_it_belongs_to})
btn.configure(text='BUTTON', width='15')
btn.grid(column='0', row='0')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-25
    • 2015-04-24
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2013-03-26
    相关资源
    最近更新 更多