如何使按钮脱离列表

How to make buttons out of list

我正在尝试编写一个代码,用图像制作按钮。每当您单击该按钮时,它都会显示该图像。

import os
from PIL import ImageTk, Image
import tkinter
root = tkinter.Tk()
folder_list = os.listdir(r"C:\Users\Teknoloji\Desktop\Phyton\Jack\Selam")

def Imagen():

    image = tkinter.Canvas(root,width=300,height=300)
    for b in folder_list:
        if b == my_text:
            img = ImageTk.PhotoImage(Image.open(f"Images\{b}"))
    label = tkinter.Label(image=img)
    print(my_text)
    label.image = img
    image.create_image(120,120,image=img)
    image.pack()

for i in folder_list:
    button = tkinter.Button(root,text=i,command=Imagen)
    my_text = button.cget("text")
    print(my_text)
    button.pack()
root.mainloop()

我已经获取了您的代码并在此处进行了一些更改:

import os
from PIL import ImageTk, Image
import tkinter

root = tkinter.Tk()
folder_list = os.listdir(r"C:\Users\Teknoloji\Desktop\Phyton\Jack\Selam")

def Imagen(img_path):
    img = ImageTk.PhotoImage(Image.open(f'images/{img_path}'))
    #label = tkinter.Label(image=img)
    image.whatever = img #keeping a reference, can be anything
    image.itemconfigure('image',image=img)
    image.pack()

for i in folder_list:
    button = tkinter.Button(root,text=i,command=lambda i=i:Imagen(i),width=10) 
    button.pack(pady=5)

image = tkinter.Canvas(root,width=300,height=300)
image.create_image(120,120,tag='image')

root.mainloop()

我都做了什么?

  • 我已经从你的代码中删除了一些不需要的部分,比如函数内部不必要的循环,而且你似乎没有使用你的标签来显示图像,而是使用 canvas,无论哪种方式我确保它不会在您按下按钮时覆盖现有图像。

  • 另外,我已经将图片路径作为参数传递给打开图片的函数,这样lambda就可以有一个参数传递给函数。

循环按钮如何工作? (摘自here

This may look magical, but here's what's happening. When you use that lambda to define your function, the open_this call doesn't get the value of the variable i at the time you define the function. Instead, it makes a closure, which is sort of like a note to itself saying "I should look for what the value of the variable i is at the time that I am called". Of course, the function is called after the loop is over, so at that time i will always be equal to the last value from the loop. Using the i=i trick causes your function to store the current value of i at the time your lambda is defined, instead of waiting to look up the value of i later. Do let me know if this works.

如果您对此有任何疑问或错误,请告诉我。

干杯