如何使用按钮打开图像,然后将该图像用作按钮的图像

时间:2019-11-10 10:17:57

标签: python-3.x user-interface tkinter

我有一个可以按的按钮,它将打开打开文件对话框。现在,我想使用按钮对话框中的图像并将其设置为按钮的图像。

from tkinter import *
from tkinter import filedialog
import schematicIO

class GUI():
    def __init__(self, root):
        self.root = root
        root.title("pix2msch")
        root.resizable(False, False)
        root.geometry("600x500")

        photo = PhotoImage(file = "background.png")
        background = Label(root, image = photo)
        background.image = photo
        background.place(x = -2, y = -2)

        self.buttonimage =  PhotoImage(file = "openimagebutton.png")
        self.open_image_b = Button(root, image = self.buttonimage, command=self.open_image, highlightthickness = 0, bd = 0, width = 256, height = 256)

        self.open_image_b.place(x = 27, y = 220)

    def open_image(self):
        root.update()
        self.file = filedialog.askopenfilename()
        self.open_image_b.config(image = PhotoImage(self.file))
        root.update_idletasks()


root = Tk()
GUI(root)
root.mainloop()

This is what the gui looks like

But this is what it looks like with an image opened

编辑:还应调整图像的大小以适合按钮,但要保持其比例

0 个答案:

没有答案