【问题标题】:Label is not filled completely标签未填满
【发布时间】:2023-02-10 23:49:53
【问题描述】:

我有以下问题:我目前正在用 python 编写一个程序,该程序使用标签来包含图像和文本。程序本身工作正常,但标签弄乱了我的图形。要将图像放在文本后面的标签中,我使用选项 compound = tkinter.CENTER。这样做的问题是由于居中,图像不再填满整个标签。这会在标签周围创建白色边框(它不是边界线。我已经尝试将其设置为 0,但没有用。我也将其设置为 2 一次,发现它周围包含不需要的空白区域)。我还应该补充一点,我现在使用相同的图片作为标签,但这不应该是这里的问题,对吗?我只知道这种方式可以在标签中的图像前面显示文本,我真的很沮丧,因为我找不到其他解决方案。由于代码的缘故,在这种情况下有必要使用标签。我隔离了这个问题,只是在这里发布了一小段代码来代表它,因为我的程序太大了,无法完整发布。

import tkinter

win = tkinter.Tk()
win.geometry("1280x720")

photo = tkinter.PhotoImage(file = "orange.png")

testLabel = tkinter.Label(win, compound = tkinter.CENTER, text = "Test", image = photo, bd = 0)
testLabel.place(x = 30, y = 30, anchor = "nw")

otherLabel = tkinter.Label(win, compound = tkinter.CENTER, text = "Other", image = photo, bd = 0)
otherLabel.place(x = 50, y = 50, anchor = "nw")

win.mainloop() 

一旦我删除 compound = tkinter.CENTER 部分,空白就消失了,但文本又不可见了。 有人可以帮帮我吗?

【问题讨论】:

  • 尝试将标签的widthheight设置为与图片相同。

标签: python image tkinter text label


【解决方案1】:

如果您按照注释中的建议将标签宽度和高度设置为固定值,则标签的大小将不会适应标签文本的长度和大小。为了使标签适应文本长度和大小,首先使用文本创建标签,然后在向其添加背景图像时使用其由 tkinter 设置的宽度和高度来保持其大小。如果图片足够大没有图像背景,标签中将没有空间。请参阅下面的代码,其中 testLabel 具有预先设置的大小,而 otherLabel 将其高度和宽度调整为放置在其中的文本的长度和大小:

import tkinter

win = tkinter.Tk()
win.geometry("480x320")

photo = tkinter.PhotoImage(file = "orange.png")

testLabel = tkinter.Label(win, compound = tkinter.CENTER, text = "Test", image = photo, bd = 0, width=50, height=15)
testLabel.place(x = 30, y = 30, anchor = "nw")

otherLabel = tkinter.Label(win, compound = tkinter.CENTER, text = "Other Test Text", bd = 0, font=('',14) )
otherLabel.place(x = 50, y = 50, anchor = "nw")
otherLabel.update()
otherLabel.config(image=photo, width=otherLabel.winfo_width(), height=otherLabel.winfo_height())

win.mainloop() 

【讨论】:

    【解决方案2】:

    但是标签弄乱了我的图形。把图像放在 文字后面的标签....

    解决问题。

    改变:

    otherLabel.place(x = 50, y = 50, anchor = "nw")
    

    到:

    otherLabel.place(x = 320, y = 50, anchor = "nw"
    

    截屏。你可以看到图像和标签:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-19
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      相关资源
      最近更新 更多