3 回答
TA贡献1836条经验 获得超5个赞
正如人们指出的那样,我需要添加card_label.image = card_image该函数并删除card_image和card_label全局以阻止图像被删除。但出于某种原因,Python 不喜欢在我这样做之前打包图像。
该函数现在看起来像这样。
global hand
card_image = ImageTk.PhotoImage(Image.open(cards[0]).resize((180, 245), Image.ANTIALIAS))
card_label = Label(root, image=card_image, relief="raised")
card_label.image = card_image
card_label.pack(side="left")
hand += cards[:1]
cards.pop(0)
print(hand)
TA贡献1788条经验 获得超4个赞
代替
card_image = ImageTk.PhotoImage(Image.open(cards[0]).resize((180, 245), Image.ANTIALIAS))
card_label = Label(root, image=card_image, relief="raised").pack(side="left")
做:
card_label = Label(root, image=card_image, relief="raised").pack(side="left")
card_image = ImageTk.PhotoImage(Image.open(cards[0]).resize((180, 245), Image.ANTIALIAS))
card_label.image = card_image #Keeps reference to the image so it's not garbage collected
请注意,当您想使用照片时,请使用变量card_image
TA贡献1824条经验 获得超5个赞
您应该使用图像池。你很幸运,我这里有一个
import os
from glob import glob
from PIL import Image, ImageTk
from typing import List, Tuple, Union, Dict, Type
from dataclasses import dataclass
@dataclass
class Image_dc:
image :Image.Image
rotate :int = 0
photo :ImageTk.PhotoImage = None
def size(self) -> Tuple[int]:
if not self.photo is None:
return self.photo.width(), self.photo.height()
return self.image.width, self.image.height
class ImagePool(object):
##__> PRIVATE INTERFACE <__##
__PATHS = dict()
__IMAGES = dict()
@staticmethod
def __name(path) -> str:
return os.path.basename(os.path.splitext(path)[0])
@staticmethod
def __unique(path:str, prefix:str='') -> str:
name = f'{prefix}{ImagePool.__name(path)}'
if name in ImagePool.names():
sol = 'using a prefix' if not prefix else f'changing your prefix ({prefix})'
msg = ("WARNING:\n"
f"{name} was not loaded due to a same-name conflict.\n"
f"You may want to consider {sol}.\n\n")
print(msg)
return None
return name
@staticmethod
def __request(name:str) -> Image_dc:
if name in ImagePool.__PATHS:
path = ImagePool.paths(name)
if os.path.isfile(path):
if name not in ImagePool.__IMAGES:
ImagePool.__IMAGES[name] = Image_dc(Image.open(path))
return ImagePool.__IMAGES[name]
else:
raise ValueError(f'ImagePool::__request - Path Error:\n\tpath is not a valid file\n\t{path}')
raise NameError(f'ImagePool::__request - Name Error:\n\t"{name}" does not exist')
return None
@staticmethod
def __size(iw:int, ih:int, w:int=None, h:int=None, scale:float=1.0) -> Tuple[int]:
if not w is None and not h is None:
if iw>ih:
ih = ih*(w/iw)
r = h/ih if (ih/h) > 1 else 1
iw, ih = w*r, ih*r
else:
iw = iw*(h/ih)
r = w/iw if (iw/w) > 1 else 1
iw, ih = iw*r, h*r
return int(iw*scale), int(ih*scale)
##__> PUBLIC INTERFACE <__##
@staticmethod
def names(prefix:str='') -> List[str]:
names = [*ImagePool.__PATHS]
return names if not prefix else list(filter(lambda name, pre=prefix: name.startswith(pre), names))
@staticmethod
def paths(name:str=None) -> Union[Dict, str]:
if name is None:
return ImagePool.__PATHS
if name in ImagePool.__PATHS:
return ImagePool.__PATHS[name]
raise NameError(f'ImagePool::paths - Name Error:\n\tname "{name}" does not exist')
@staticmethod
def images(name:str=None, prefix:str='') -> Union[Dict, Image.Image]:
if name is None:
return {name:ImagePool.__request(name).image for name in self.names(prefix)}
return ImagePool.__request(name).image
@staticmethod
def photos(name:str=None, prefix:str='') -> Union[Dict, ImageTk.PhotoImage]:
if name is None:
return {name:ImagePool.__request(name).photo for name in self.names(prefix)}
return ImagePool.__request(name).photo
@staticmethod
def append_file(path:str, prefix:str='') -> Type:
if not os.path.isfile(path):
raise ValueError(f'ImagePool::append_file - Value Error:\n\tpath is not valid\n\t{path}')
name = ImagePool.__unique(path, prefix)
if name:
ImagePool.__PATHS[name] = path
return ImagePool
@staticmethod
def append_directory(directory:str, filters=['*.png', '*.jpg'], prefix:str='') -> Type:
if not os.path.isdir(directory):
raise ValueError(f'ImagePool::append_directory - Value Error:\n\tdirectory is not valid\n\t{directory}')
filters = filters if isinstance(filters, (List, Tuple)) else [filters]
for filter in filters:
for path in glob(f'{directory}/{filter}'):
ImagePool.append_file(path, prefix)
return ImagePool
@staticmethod
def photo(name:str, width:int=None, height:int=None, scale:float=1.00, rotate:int=None) -> ImageTk.PhotoImage:
image_t = ImagePool.__request(name)
size = ImagePool.__size(*image_t.size(), width, height, scale)
rotate = image_t.rotate if rotate is None else rotate
#only resize if the new size or rotation is different than the current photo size or rotation
#however, a small margin for error must be considered for the size
diff = tuple(map(lambda i, j: i-j, image_t.size(), size))
if (diff > (1, 1)) or (diff < (-1, -1)) or (image_t.rotate != rotate):
image_t.rotate = rotate
image_t.photo = ImageTk.PhotoImage(image_t.image.resize(size, Image.LANCZOS).rotate(rotate))
return image_t.photo
使用该文件您可以非常轻松地做很多事情。您可以将所有卡片图像放入一个文件夹中,并通过以下方式获取它们:
ImagePool.append_directory(path_to_folder)
然后,您可以获取任何卡并强制其适合其父级(无论如何):
somelabel['image'] = ImagePool.photo(image_name, allotted_width, allotted_height)
要不就:
somelabel['image'] = ImagePool.photo(image_name)
你可以得到池中每个名字的列表
deck = ImagePool.names()
或者在附加目录的同时抓取它
deck = ImagePool.append_directory(path_to_folder).names()
这对您非常有帮助,因为您可以简单地洗牌并弹出该列表作为游戏中的官方“牌组”。像这样:
somecard['image'] = ImagePool.photo(deck.pop(0))
假设您不仅拥有卡片图形,但又不想在创建牌组时获得所有图像,那么也有一个解决方案。
首先在附加卡片图像目录时提供前缀,然后在调用names(). 只要卡片图像目录中只有卡片图像,则只会返回卡片名称。
deck = ImagePool.append_directory(path_to_folder, prefix='cards_').names('cards_')
笔记:
allotted区域仅被分配,绝不应被假定为代表实际图像的最终宽度和/或高度。图像将尽一切努力适应分配的空间,而不会丢失其原始的高度和宽度比例。如果您不提供分配的宽度和高度,图像将是完整尺寸。
所有图像和照片参考都会自动维护在ImagePool. 没有理由存储您自己的参考资料
整个类是静态的,因此可以在任何地方访问所有图像和照片的引用,而无需ImagePool实例。换句话说,您永远不需要这样做:images = ImagePool()因此永远不需要弄清楚如何进入images某些class或其他文档。
在您开始请求图像之前,不会实际加载图像,然后它会自动发生。这是一件好事。你有 52 张卡,但如果你在第一场比赛中只使用 ex: 6 ~ 只有 6 张会完全加载。最终,所有卡牌都会被玩完并被完全加载,并且您在游戏中不会出现尝试一次完全创建 52 张卡牌的情况。
该类ImagePool具有更多功能,但此处解释的功能是您的游戏所需的全部功能。
添加回答
举报