Skip to main content
 首页 » 编程设计

python之列表中的两个随机值需要与图像匹配

2024年12月31日9me-sa

背景: 我的 Tkinter 应用程序中有一个小功能,它从列表中随机化两个随机值并将它们打印到 GUI。但我正在努力获得具有随机值的正确图像(团队 Logo )。

目标: 是随机团队名称(来自 28 个团队的列表)并且 GUI 也应该显示团队标志。按下“RANDOM”按钮,它会生成 Team1 和 Team2,两者都应该在文本旁边有 Logo 。

我已经研究过:我有时间回答这个问题,但我无法弄明白。这个骰子游戏有点像,但我需要两个值而不是一个值,而且我的列表中充满了字符串。

示例:https://stackoverflow.com/a/27913052/5132305

import random 
import tkinter as tk 
from PIL import ImageTk, Image 
 
 # Use a class that hold all Team data 
class Team(): 
   def __init__(self, name, img_filename): 
    self.name = name 
    self.img_filename = img_filename 
 
   @property 
   def image(self): 
    # TODO: Open image file and return .PhotoImage object 
    team_logo = Image.open("%s.jpg" % (self.img_filename)) 
    render = ImageTk.PhotoImage(team_logo) 
    self.img_filename.image = render 
    return self.img_filename 
 
   #This is how the class prints 
   def __str__(self): 
    return "Name: {} Image:{}".format(self.name, self.img_filename) 
 
 
class MainWindow(tk.Frame): 
      def __init__(self, parent, *args, **kwargs): 
       tk.Frame.__init__(self, parent,  *args, **kwargs) 
       root.geometry("700x450") 
       text_1 = tk.Label(text="VS", fg="red", anchor="center") 
       text_1.place(relx=.5, rely=.5, anchor="center") 
       text_2 = tk.Label(text="RANDOM GAME", fg="green", anchor="n") 
       text_2.pack(side="top") 
 
       # Button for randomize 
       self.parent = parent 
       self.frame = tk.Frame(self.parent) 
       self.randomButton = tk.Button(self.frame, text = 'RANDOM',  
       command=self.genRanTeam) 
       self.randomButton.pack(side="bottom") 
       self.frame.pack(side="bottom") 
 
       self.home_name = tk.StringVar() 
       self.visitor_name = tk.StringVar() 
 
       if 0: # TODO: Implement Team.image 
           # Images, I should somehow use this with home/visitor label? 
           # Yes, look at TODO in def genRanTeam(... 
 
           load = Image.open("%s.jpg" % (self.home.image)) 
           render = ImageTk.PhotoImage(load) 
           # ONLY, if you decide to use OWN Label for Image 
           # What you suggest for this? So if I decide to only use home/visitor labels, I don't need next 4 lines of code (after this text?) 
           self.team_logo = tk.Label(parent, image=render) 
           self.team_logo.image = render 
       else: 
           self.team_logo = None 
 
 
       # Home team 
       self.home_label = tk.Label(Image = self.team_logo, textvariable=self.home_name)  
       self.home_label.pack(side="left") 
       # Visitor team 
       self.visitor_label = tk.Label(Image = self.team_logo, textvariable=self.visitor_name)  
       self.visitor_label.pack(side="right") 
 
       self.__init__Teams() 
 
      # Hold this in a own function for brevity 
      def __init__Teams(self): 
        self.teams = [Team('Chicago Fire', 'chicago'), Team('New York \ 
        Red Bulls', 'newyork'), Team('Philadelphia Union', 'phila'),  
        Team('Toronto FC', 'toronto')] 
        # Init defaults 
        self.home = self.teams[0] 
        self.visitor = self.teams[0] 
 
      def genRanTeam(self): 
        # Use the initalized Teams from MainWindow..__init__ 
        self.__init__Teams() 
        self.home = random.choice(self.teams) 
        self.visitor = None 
        # Loop while home == visitor 
        while self.visitor is None or self.home.name is self.visitor.name: 
         self.visitor = random.choice(self.teams) 
 
        self.home_name.set(self.home.name) 
        self.visitor_name.set(self.visitor.name)    
 
        # TODO: Configure .team_label with Team.image 
        # self.home_label.configure(image=self.home.image) 
        self.home_label.configure(image=self.home.image) 
        self.visitor_label.configure(image=self.visitor.image) 
 
if __name__ == "__main__": 
         root = tk.Tk() 
         main = MainWindow(root) 
         main.pack(side="top", fill="both", expand=True) 
         root.mainloop() 

现在,当我按下 RANDOM 按钮时,它会对列表中的变量 x 和 y 随机正确取值。

我在文件夹 project/images 中也有 28 张图片。所有图片均为“team_name.jpg”

问题 1:如何循环列出并匹配团队名称和 Logo ?

感谢所有帮助,一些代码审查也很棒! (SO 中的第一个问题!)

请您参考如下方法:

Comment: Implement Team.image

运行你的 Team.image 给我:

self.img_filename.image = render 
AttributeError: 'str' object has no attribute 'image' 

您不能向构建str 对象添加新属性。 这将起作用,更改为:

self.render = ImageTk.PhotoImage(team_logo) 
return self.render 

Comment: Do I need to make another tk.Label for team image?

不需要这样做,这取决于你想要的布局。
从一个开始 tk.Label(self, image=image, textvariable=name)
这看起来像:
相关:label-on-top-of-image-in-python

Comment: Is it possible that self.visitor can show team+logo?

显示任何东西不是 class Team() 的功能,而是 tk.Lable(... 的工作。
相关:updating-tkinter-label-with-an-image


Question: Two random values from list needs to match with images

这种方法不使用两个列表,它在一个类中定义两个值(团队名称、团队形象)。因此不需要匹配。
例如:

# Use a class that hold all Team data 
class Team(): 
    def __init__(self, name, img_filename): 
        self.name = name 
        self.img_filename = img_filename 
 
    # This is how the class prints 
    def __str__(self): 
        return "Name: {} Image:{}".format(self.name, self.img_filename) 
 
class MainWindow(tk.Frame): 
    def __init__(self, parent, *args, **kwargs): 
 
        # Up to 28 teams - Defined in __init__ only once 
        # Create a list with all Teams using class Team 
        self.teams = [Team('Chicago Fire', 'logo1.jpg'), Team('New York Red Bulls', 'logo2.jpg'), Team('Philadelphia Union', 'logo3.jpg'), Team('Toronto FC', 'logo4')] 
        # Init defaults 
        self.home = self.teams[0] 
        self.visitor = self.teams[0] 
 
    def genRanTeam(self): 
        # Use the initalized Teams from __init__ 
        self.home = random.choice(self.teams) 
 
        self. visitor = None 
        # Loop while home == visitor 
        while self.visitor is None or self.home is self.visitor: 
            self.visitor = random.choice(self.teams) 
 
if __name__ == "__main__": 
    import time 
 
    root = tk.Tk() 
    main = MainWindow(root) 
    for _ in range(3): 
        main.genRanTeam() 
        print("home:{} :\tvisitor:{}".format(main.home, main.visitor)) 
        time.sleep(1) 

Output:

home:Name: Toronto FC Image:logo4 : visitor:Name: Chicago Fire Image:logo1.jpg 
home:Name: New York Red Bulls Image:logo2.jpg : visitor:Name: Toronto FC Image:logo4 
home:Name: Toronto FC Image:logo4 : visitor:Name: New York Red Bulls Image:logo2.jpg 

使用 Python 测试:3.4.2