无法使用锚定义按钮内容也不能使用对齐定位按钮内容

问题描述 投票:0回答:2

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

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

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

_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)

(我不会同时使用对齐和锚点,我只是将它们一起发布给你,告诉我我使用它的方式)我会发布我的应用程序的图片供你注意。我的客户不仅要切换图像,该图像说明了某些服务的状态,还包括附近的文本信息。 enter image description here

python-3.x tkinter ttk
2个回答
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()

Result


0
投票

来自@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
    )
© www.soinside.com 2019 - 2024. All rights reserved.