簡體   English   中英

如何獲取已分配給小部件的圖像變量?

[英]How to get the image variable that has been assigned to a widget?

如何獲取按鈕myBtn的圖像變量。

from tkinter import *

master = Tk()
FiveStarsImg = PhotoImage(file=r"D:\Users\Jean Paul\OneDrive\Programming\JP\Programs\Prog 7 - Generals Online Game\Characters\1- Five stars.png")

myBtn = Button(master, image=FiveStarsImg)
master.mainloop()

如果我打印myBtn['image']它只返回pyimage ,但我需要它返回圖像變量名稱FiveStarsImg

我該怎么做?

我不知道有任何方法可以返回實際變量名稱,但如果您將所有值存儲在列表中,您始終可以通過索引引用它們或遍歷存儲的名稱。

這是一個例子。

我有 4 張圖像存儲在一個名為 images 的文件夾中。

我將索引、文件路徑、圖像、按鈕和標簽存儲在列表中。 我使用 lambda 來保存這組信息的索引,以便我們可以引用存儲的列表來比較值。

在這種情況下,我創建了一個函數,用於檢查每個圖像是否與單擊的按鈕大小相同。

如果您想使用與我相同的圖像進行測試,這里是圖像。

暗紅色 - Copy.png 暗紅色.png 灰色.png graybg.png

這是代碼。 確保更改正在搜索的圖像目錄或為圖像創建目錄。

import tkinter as tk
import os
import cv2


master = tk.Tk()
image_list = []


def check_all(i):
    for image_group in image_list:
        im1 = cv2.imread(image_list[i][1])
        im2 = cv2.imread(image_group[1])
        if im1.shape == im2.shape:
            image_group[4]['text'] = f"image matches size {image_list[i][1]}"
        else:
            image_group[4]['text'] = f"does not match size"

ndex = 0
for filename in os.scandir(r".\images"):
    if filename.is_file():
        img = tk.PhotoImage(file=filename.path)
        image_list.append([ndex, filename.path, img,
                           tk.Button(master, image=img, command=lambda i=ndex: check_all(i)),
                           tk.Label(master, text='Label for checking images against each other')])
        image_list[-1][3].grid(row=ndex, column=0)
        image_list[-1][4].grid(row=ndex, column=1)
        ndex += 1


master.mainloop()

結果:

例如,如果我選擇第一個圖像按鈕,第一個按鈕右側的標簽將更改為“圖像匹配大小”,而其他 3 個將顯示“大小不匹配”

在此處輸入圖像描述

如果我選擇第二個按鈕,它將匹配第二個和第三個按鈕的大小,因為這兩個圖像的尺寸相同。

在此處輸入圖像描述

所有這些都是為了說明您可以將所有內容存儲在列表中以動態管理按鈕和/或使用存儲的圖像在以后的代碼中進行比較。

如果您有任何問題,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM