【问题标题】:Cannot position button content neither with anchor nor with justify既不能用锚也不能用 justify 定位按钮内容
【发布时间】:2019-03-14 13:20:18
【问题描述】:

我有动态按钮标签,每次点击它都会改变。问题是,当按钮上的文本发生变化时,按钮宽度也是如此。为此,我为按钮设置了固定宽度。

之后,又出现了一个问题。内容以按钮为中心,因此每次更改图像和标签都会移动一点。出于这个原因,我尝试将所有内容都放在左侧以减少内容抖动。

我查看了文档,发现按钮小部件支持定位内容的锚选项。但是,当我尝试时,我收到了错误:

_tkinter.TclError: 未知选项“-anchor”

我找到了另一种选择,证明,但结果是一样的:

_tkinter.TclError: 未知选项“-justify”

有人知道怎么处理吗?我将与您分享我的代码:

self.btnServiceIo = ttk.Button(
    top_buttons_frame,
    text="Usługa automatyczna",
    image=self.ioBtnImg_off,
    compound=tk.LEFT,
    width=30,
    justify=tk.LEFT,
    anchor='w')
self.btnServiceIo.pack(side=tk.LEFT)
self.btnServiceIo.bind("<ButtonRelease>", self.IObuttonToggle)

(我没有同时使用 justify 和 anchor,我只是将它们放在一起,向您展示我的使用方式) 我将发布我的应用程序的图片以供您注意。我的客户不仅想要显示某些服务状态的切换图像,还想要附近的文本信息。

【问题讨论】:

  • 如果您包含一个小的minimal reproducible example,您的问题会更好。
  • tkinter 按钮支持锚定和对齐,但您使用的是 ttk 按钮。

标签: python-3.x tkinter ttk


【解决方案1】:

对于 ttk 按钮,您可以在 ttk 样式中设置锚选项,请参阅anchor entry on this page

例如:

import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk

root = tk.Tk()

s = ttk.Style()
s.configure('TButton', anchor=tk.W)

buttonImage = Image.open('test.png')
buttonPhoto = ImageTk.PhotoImage(buttonImage) 

btnServiceIo = ttk.Button(
    root,
    text="Usługa automatyczna",
    image=buttonPhoto,
    compound=tk.LEFT,
    width=30)
btnServiceIo.pack(side=tk.LEFT)

root.mainloop()

【讨论】:

【解决方案2】:

来自@fhdrsdg 的回答几乎是完美的,但它与我的一些仅带有文本的简单按钮相混淆,并以按钮为中心。我必须为我的按钮制作专用样式,如下所示:

# Access ttk style object
s = ttk.Style()

# Set dedicated style for button, derived from main button class
s.configure('service-io.TButton', anchor=tk.W)

self.ioBtnImg_off = tk.PhotoImage(file='../img/io.png')
self.ioBtnImg_on = tk.PhotoImage(file='../img/io_on.png')
self.btnServiceIo = ttk.Button(
    top_buttons_frame,
    text="Usługa automatyczna",
    image=self.ioBtnImg_off,
    compound=tk.LEFT,
    width=30,
    style='service-io.TButton' # use dedicated style
    )

【讨论】:

    猜你喜欢
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多