Welcome 歡迎光臨! 愛上網路-原本退步是向前 !

tkinter Canvas create_image 繪製影像

在繪製影像時可以調整 anchor 參數,anchor 參數是設定影像輸出在該區域的位置,預設是 anchor=tk.CENTER 表示會以傳入的座標為影像中心,這邊我們改成 anchor=nw表示傳入的該座標為影像的左上角,如下例中的 (0,0) 為影像的左上角。

nw:左上
n:上
ne:右上
w:左
center:中
e:右
sw:左下
s:下
se:右下

======================

        try: 
            image_path = cwd+os_path_char+"ar30root2.png"  # Make sure to have an image file in the same directory 
            print(image_path) 
            image = Image.open(image_path) 

            #取得 原始圖 的原始尺寸
            src_width, src_height = image.size

            # Convert the PIL image to a Tkinter PhotoImage             
            photo = ImageTk.PhotoImage(image.resize((image_w,image_h)))             
             
            canvas = Canvas(self.master, width=image_w, height=image_h)             
            canvas.pack() 
            canvas.create_image(1, 1,anchor='nw', image=photo) 
            canvas.tk_img= photo #要更新否則會産生不出圖
             
 
        except FileNotFoundError: 
            print(f"Error: {image_path} not found. Please check the file path.") 
            exit() 

========================

 canvas.create_image(0, 0, anchor='nw', image=photo)   # 建立圖片
 canvas.tk_img = photo               # 修改屬性更新畫面

==========================

def draw_box(wp,hp):
    x1, y1,x2, y2=384,5,487, 190

draw_button = tk.Button(root, text="Draw Box", command=lambda:draw_box(image_w_p,image_h_p)   )

======================================================================

先刪除再繪製

            canvas.delete('tagname')

            for i in arkey:              

                x1, y1,x2, y2=map(int , arr_box[i].split(",") )

                canvas.create_rectangle(x1*w_p, y1*h_p, x2*w_p, y2*h_p, outline="blue", width=3, fill="",tags='tagname')

[ Python ] 瀏覽次數 : 46 更新日期 : 2026/01/04