如何在tkinter中显示来自列表或文件夹的随机图像,并允许用户输入其名称。

huangapple go评论147阅读模式
英文:

how to i show a random image from a list or folder on tkinter and have a user input the name of it

问题

你可以尝试使用PIL库(Pillow)来加载并显示随机的图像。以下是一个示例修改:

from PIL import Image, ImageTk

# 在easy_level()函数中
def easy_level():
  new = Toplevel(window)
  new.title("Easy Mode")
  new.configure(background=bg1)
  new.geometry("600x500")

  ans = tk.Entry(new, font=('Times', 25))
  ans["justify"] = "center"
  ans["borderwidth"] = "1px"
  ans.place(x=90, y=270, width=414, height=188)

  rules1 = tk.Label(new, font=('Times', 20), bg=bg1)
  rules1["text"] = "Enter Country Name Here:"
  rules1["justify"] = "center"
  rules1.place(x=110, y=230)

  # 随机选择并显示图像
  path = "flags"
  files = os.listdir(path)
  random_image = random.choice(files)
  image_path = os.path.join(path, random_image)
  flag_image = Image.open(image_path)
  flag_photo = ImageTk.PhotoImage(flag_image)

  flag_label = tk.Label(new, image=flag_photo, bg=bg1)
  flag_label.image = flag_photo  # 保持图像引用,以免被垃圾回收
  flag_label.place(x=150, y=20)

# 其他难度级别的函数 medium_level() 和 hard_level() 可以类似地修改

这样,你可以在不同的难度级别中显示随机的国旗图像。不要忘记导入PIL库,如果还没有安装,可以使用pip install Pillow来安装它。

英文:

basically im trying to create a flag guessing game but im having problems with showing the images onto the certain levels. when someone clicks a certain level i want a random flag to show and the user to guess the name. but ive tried a few things and none work so far idk what im doing wrong or how to call the images.

the full code:

import tkinter as tk
import tkinter
import random
from tkinter import *
from tkinter import ttk, Canvas, NW
from PIL import ImageTk, Image
import os

window = tk.Tk()
window.title("Flags Guessing Game")
window.geometry("600x500")
bg = '#d9b9e2'
bg1 = '#b9e2df'
bg2 = '#e2b9d0'
bg3 = '#dbe2b9'
window.configure(background=bg)


def level_pick():
  ebtn=tk.Button(window,font=('Times', 30), command=easy_level)
  ebtn["bg"] = "#b6d6ff"
  ebtn["justify"] = "center"
  ebtn["text"] = "Easy"
  ebtn.place(x=10,y=170,width=282,height=145)

  mbtn=tk.Button(window,font=('Times', 30), command=medium_level)
  mbtn["bg"] = "#f9ffa8"
  mbtn["justify"] = "center"
  mbtn["text"] = "Medium"
  mbtn.place(x=310,y=170,width=277,height=145)

  hbtn=tk.Button(window,font=('Times', 30), command=hard_level)
  hbtn["bg"] = "#ffb3fc"
  hbtn["justify"] = "center"
  hbtn["text"] = "Hard"
  hbtn.place(x=150,y=330,width=282,height=145)
  
  diflbl=tk.Label(window,font=('Times', 20),bg=bg)
  diflbl["text"] = "Choose a difficulty:"
  diflbl["justify"] = "center"
  diflbl.place(x=160,y=100)

  titlelbl=tk.Label(window,font=('Times', 25),bg=bg)
  titlelbl["text"] = "Flag Guessing Game"
  titlelbl["justify"] = "center"
  titlelbl.place(x=110,y=40)


def easy_level():
  new = Toplevel(window)
  new.title("Easy Mode")
  new.configure(background=bg1)
  new.geometry("600x500")
  
  ans=tk.Entry(new,font=('Times', 25))
  ans["justify"] = "center"
  ans["borderwidth"] = "1px"
  ans.place(x=90,y=270,width=414,height=188)

  rules1=tk.Label(new, font=('Times', 20),bg=bg1)
  rules1["text"] = "Enter Country Name Here:"
  rules1["justify"] = "center"
  rules1.place(x=110,y=230)
  
  
  #easyimg = ["flags/canada.jpg","flags/spain.jpg","flags/mexico.jpg"]

  # show random image
  path="flags"
  files=os.listdir(path)
  d=random.choice(files)
  os.system(d)

def medium_level():
  new = Toplevel(window)
  new.title("Medium Mode")
  new.configure(background=bg2)
  new.geometry("600x500")
  
  ans=tk.Entry(new,font=('Times', 25))
  ans["justify"] = "center"
  ans["borderwidth"] = "1px"
  ans.place(x=90,y=270,width=414,height=188)

  rules2=tk.Label(new, font=('Times', 20),bg=bg2)
  rules2["text"] = "Enter Country Name Here:"
  rules2["justify"] = "center"
  rules2.place(x=110,y=230)

def hard_level():
  new = Toplevel(window)
  new.title("Hard Mode")
  new.configure(background=bg3)
  new.geometry("600x500")
  
  ans=tk.Entry(new,font=('Times', 25))
  ans["justify"] = "center"
  ans["borderwidth"] = "1px"
  ans.place(x=90,y=270,width=414,height=188)

  rules3=tk.Label(new, font=('Times', 20),bg=bg3)
  rules3["text"] = "Enter Country Name Here:"
  rules3["justify"] = "center"
  rules3.place(x=110,y=230)

level_pick()
tk.mainloop()

this is one of the things i tried:

  path="flags"
  files=os.listdir(path)
  d=random.choice(files)
  os.system(d)

答案1

得分: 0

以下是已翻译的部分:

这里是一个简单的演示,展示了使用tkinterPillow获取和显示随机图像的基本操作。为了使示例正确运行,.py文件应该与另一个名为"FlagPics"的文件夹位于同一级别。"FlagPics"文件夹应包含3个图像:"FirstFlag.png","SecondFlag.png"和"ThirdFlag.png"。这些图像可以是任何东西:只需将它们重命名为上述名称,或者在代码中更改图像名称以匹配您的图像的实际名称。

列表pics包含对"FlagPics"文件夹中的3个图像的引用,使用了在这里记录的Pillow方法:https://www.pythontutorial.net/tkinter/tkinter-photoimage/。当您运行.py文件时,最初显示的图像将从pics列表中随机选择,并且每次用户单击按钮时,都会从相同的列表中选择一个新的随机图像。

请注意,图像是由tkinterLabel小部件显示的,因为您将Labelimage属性设置为ImageTk.PhotoImage的一个实例。其他tkinter小部件也可以显示图像 - 例如ButtonCanvas小部件(相关问题在这里:https://stackoverflow.com/questions/43009527/how-to-insert-an-image-in-a-canvas-item)。

现在您已经显示了随机图像,您可能还对如何调整它们的大小感兴趣:https://www.geeksforgeeks.org/how-to-resize-image-in-python-tkinter/

*所有的创意归用户acw1668所有 - 我只是构建了一个可运行的示例。

英文:

Here is a simple demonstration* showing the basics of getting and displaying a random image with tkinter and Pillow. For the example to run correctly, the .py file should be in a folder at the same level as another folder named "FlagPics." The "FlagPics" folder should contain 3 images: "FirstFlag.png," "SecondFlag.png," and "ThirdFlag.png." These images can be anything: just rename them as above, or change the image names in the code to match your images' actual names.

The list pics contains references to the 3 images in the "FlagPics" folder, created using the Pillow methods documented here: https://www.pythontutorial.net/tkinter/tkinter-photoimage/. The picture which is initially displayed when you run the .py file will be randomly chosen from the pics list, and every time the user clicks the button, a new random picture will be selected from the same list.

Note that the image is displayed by the tkinter Label widget, since you set the Label's image property to an instance of ImageTk.PhotoImage. Other tkinter widgets can also display images - examples include the Button and Canvas widgets (related question here: https://stackoverflow.com/questions/43009527/how-to-insert-an-image-in-a-canvas-item).

import tkinter as tk
from PIL import ImageTk, Image
from random import randint

window = tk.Tk()
window['width'] = 400
window['height'] = 400

pics = [ImageTk.PhotoImage(Image.open("FlagPics/FirstFlag.png")),
        ImageTk.PhotoImage(Image.open("FlagPics/SecondFlag.png")),
        ImageTk.PhotoImage(Image.open("FlagPics/ThirdFlag.png"))]

def rerandomize(label):
    label['image'] = pics[randint(0, 2)]

flagLabel = tk.Label(master=window, image=pics[randint(0, 2)])
flagLabel.place(relx=0.25, rely=0.25, relheight=0.5, relwidth=0.5)

rerandomizeButton = tk.Button(window, text="Rerandomize", command = lambda: rerandomize(flagLabel))
rerandomizeButton.place(relx=0.35, rely=0.85, relheight=0.1, relwidth=0.3)

window.mainloop()

Now that you have your random images displayed, you may also be interested in how to resize them: https://www.geeksforgeeks.org/how-to-resize-image-in-python-tkinter/

*Full credit goes to user acw1668 for the idea - I only constructed a runnable example.

huangapple
  • 本文由 发表于 2023年6月9日 10:21:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定