我试图在 tkinter 中画布内的图像上绘制一个简单的矩形,但它没有绘制。没有错误。
是因为我放置图像时没有使用
canvas.create_image
吗?因为我正在框架内绘制图像,并将框架放置在画布内。这是通过滚动功能打开完整图像的唯一方法。
这是代码:
import tkinter as tk
from PIL import ImageTk, Image
root = tk.Tk()
# Tkinter widgets needed for scrolling. The only native scrollable container that Tkinter provides is a canvas.
# A Frame is needed inside the Canvas so that widgets can be added to the Frame and the Canvas makes it scrollable.
canvas = tk.Canvas(root)
fTable = tk.Frame(canvas)
hor_scroll_bar = tk.Scrollbar(root)
ver_scroll_bar = tk.Scrollbar(root)
# Updates the scrollable region of the Canvas
def updateScrollRegion():
canvas.update_idletasks()
canvas.config(scrollregion=fTable.bbox())
# Sets up the Canvas, Frame, and scrollbars for scrolling
def createScrollableContainer():
canvas.config(xscrollcommand=hor_scroll_bar.set,yscrollcommand=ver_scroll_bar.set, highlightthickness=0)
hor_scroll_bar.config(orient=tk.HORIZONTAL, command=canvas.xview)
ver_scroll_bar.config(orient=tk.VERTICAL, command=canvas.yview)
hor_scroll_bar.pack(fill=tk.X, side=tk.BOTTOM, expand=tk.FALSE)
ver_scroll_bar.pack(fill=tk.Y, side=tk.RIGHT, expand=tk.FALSE)
canvas.pack(fill=tk.BOTH, side=tk.LEFT, expand=tk.TRUE)
canvas.create_window(0, 0, window=fTable, anchor=tk.NW)
# Adding an image
def addNewLabel():
img = ImageTk.PhotoImage(file="test.jpg")
tk.Label(fTable, image=img).grid(row=0, column=0)
canvas.img = img
canvas.create_rectangle(0, 0, 100, 100, fill="blue")
# Update the scroll region after new widgets are added
updateScrollRegion()
createScrollableContainer()
addNewLabel()
root.mainloop()
谢谢你
问题似乎与您尝试在画布上绘制矩形的方式有关。使用包含可滚动框架的画布时,绘制形状时必须使用相对于画布本身而不是框架的坐标。
下面,您将找到 addNewLabel() 函数的调整版本:
def addNewLabel():
img = ImageTk.PhotoImage(file="test.jpg")
label = tk.Label(fTable, image=img)
label.grid(row=0, column=0)
# Save a reference to the image to prevent it from being garbage collected
label.img = img
canvas.create_rectangle(10, 10, 110, 110, fill="blue") # Coordinates relative to the canvas
# Update the scroll region after new widgets are added
updateScrollRegion()
我已经将 create_rectangle 函数的坐标调整为相对于画布。尝试一下修改后的代码,您应该会观察到画布上绘制的蓝色矩形。请随意微调坐标,将矩形精确定位在您想要的位置。