简体   繁体   English

Python Tkinter 按钮 - 分别对齐/锚文本/标签和图标

[英]Python Tkinter Button - Justify/Anchor text/label and icon separately

I am working on a Tkinter application where I need a menu list.我正在开发一个 Tkinter 应用程序,我需要一个菜单列表。

I have a list of buttons created that have a Text label, and an Icon.我创建了一个按钮列表,其中包含一个文本 label 和一个图标。

I can successfully justify and anchor the text to the left (West) so that the text is lined up nicely.我可以成功地将文本对齐并锚定到左侧(西),以便文本很好地排列。

Unfortunately since the menu has different length words, the icon is just on the end and does not line up.不幸的是,由于菜单有不同长度的单词,图标就在最后并且没有对齐。

Is there a way in a Tkinter button to justify and anchor the text separately from the icon? Tkinter 按钮中是否有一种方法可以将文本与图标分开进行对齐和锚定? So the text/label can be on the West, and the Icon can be on the right, so everything lines up in the menu list.所以文本/标签可以在西边,图标可以在右边,所以菜单列表中的所有内容都对齐。

An easy way is get the maximum of those length of words first.And fill those which is not the longest with space.Don't know whether it is the best way.like:一种简单的方法是先获取最大长度的单词。然后用空格填充那些不是最长的单词。不知道这是否是最好的方法。喜欢:

import tkinter as tk

root = tk.Tk()
img = tk.PhotoImage(file="xxxx")

textList = ["open", "setting", "close"]
maxLength = max(map(len, textList)) # get the maximum of length

for i in textList:
    btn = tk.Button(root, text=i.ljust(maxLength), font=("Consolas",10),image=img, compound=tk.RIGHT)
    btn.pack()
root.mainloop()

PS : You need to use monospaced font,and make sure your icon has the same size.If not, consider use PIL.Image.resize() . PS :您需要使用等宽字体,并确保您的图标具有相同的大小。如果不是,请考虑使用PIL.Image.resize()

I am working on a Tkinter application where I need a menu list.我正在开发需要菜单列表的 Tkinter 应用程序。

I have a list of buttons created that have a Text label, and an Icon.我有一个创建的按钮列表,其中包含一个文本 label 和一个图标。

I can successfully justify and anchor the text to the left (West) so that the text is lined up nicely.我可以成功地证明文本的合理性并将其锚定到左侧(西部),以便文本很好地排列。

Unfortunately since the menu has different length words, the icon is just on the end and does not line up.不幸的是,由于菜单有不同长度的单词,图标就在最后,没有排成一行。

Is there a way in a Tkinter button to justify and anchor the text separately from the icon? Tkinter 按钮中是否有办法将文本与图标分开对齐和锚定? So the text/label can be on the West, and the Icon can be on the right, so everything lines up in the menu list.所以文本/标签可以在西方,图标可以在右边,所以菜单列表中的所有内容都排成一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM