这是我的第一篇文章。我经常访问堆栈溢出,以前总是能找到所有问题的答案,但今天不行。
我尝试在窗口中将图像显示为标签,但这不是我想象的 Tkinter 显示它们的方式。换句话说。我有几张小图像,它们应该彼此相邻放置,没有任何间隙。但除了我的所有努力之外,Tkinter 总是在两个相邻元素之间放置小边框或间隙(可能 1-2 像素)。
from tkinter import *
from tkinter import ttk
class MainWindow():
def __init__(self, mainWidget):
self.status_bar_text = StringVar()
self.status_bar_text.set('')
self.image_to_place = PhotoImage(file='my_image.png')
self.main_frame = ttk.Frame(mainWidget, width=768, height=480, padding=(0, 0, 0, 0))
self.main_frame.place(x=0, y=0)
self.status_bar = ttk.Label(mainWidget, width=768, border=1, anchor=W, relief=SUNKEN, textvariable=self.status_bar_text)
self.status_bar.place(x=0, y=480)
self.main_gui()
def main_gui(self):
i = 0
plate_cords = [[0, 0], [24, 0], [48, 0], [72, 0], [96, 0], [120, 0]]
for plate in plate_cords:
self.wall_label = ttk.Label(self.main_frame, image=self.image_to_place)
self.wall_label.place(x=plate_cords[i][0], y=plate_cords[i][1])
i += 1
del i
def main():
global root
root = Tk()
root.title('Title')
root.geometry('768x500+250+100')
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
window = MainWindow(root)
window
root.mainloop()
if __name__ == '__main__':
main()
我尝试了“borderwidth”、“padding”、“bordermode”等选项以及其他一些技巧,但似乎没有任何效果符合我的预期。感谢您的任何帮助和想法。
有两个属性需要设置为 0(零):
borderwidth
和 highlightthickness
。 borderwidth
(与 relief
)定义小部件的实际边框。 highlightthickness
还定义了某种边框——它是一个矩形环,当小部件获得焦点时可见。
我的图像宽度为 237x37 高度。
from tkinter import*
import tkinter as tk
from tkinter import font
top = Tk()
top.geometry("800x480")
top.title('FLOW')
C = Canvas(top, bg="#0026D1", height=480, width=800)
LabelsFont = font.Font(family='DejaVu Sans', size=10, weight='bold')
filenameLabel1 = PhotoImage(file = "/home/autorun/Desktop/pictures/štítok1.png")
Label1 = tk.Label(top, wraplength = 230, font=LabelsFont, fg="white", text="PRETLAK NA VSTUPE",image=filenameLabel1,borderwidth=0,compound="center",highlightthickness = 0,padx=0,pady=0)
Label1.place(x=15,y=90)
C.pack()
top.mainloop()
如果Label1.place中没有宽度和高度,则必须使用pady=0,padx=0,borderwidth=0,highlightthickness = 0,或者必须使用Label1.place宽度和高度为borderwidth=0,highlightthickness =的图片0.
我的代码中的第二种方式:
Label1 = tk.Label(top, wraplength = 230, font=LabelsFont, fg="white", text="PRETLAK NA VSTUPE",image=filenameLabel1,borderwidth=0,compound="center",highlightthickness = 0)
Label1.place(x=15,y=90,width=237,height=37)
这篇文章已经变得很老了,但如果人们仍然阅读它,我发现将标签的“border”属性设置为 False 也可以(而不是“走很长的路”)
label = tk.Label(...., border = False)
对我来说这效果更好:
Label(..., state='normal')