单击按钮时更新画布图像

时间:2019-10-25 09:27:18

标签: python-3.x tkinter

当我点击按钮时,我正在尝试修改画布上显示的图像。 我有一个对象“ Window”,其中将包含我的窗口层。该对象包含一个名为“ draw_frame”的画布和一个名为“ source_button”的按钮。我将命令“ self.load_static_source”添加到我的按钮中,但是当我单击按钮时什么也没发生。

(不完全是什么,因为我试图在 init 范围内添加默认背景,并且当我单击按钮后,画布上的图像刚刚消失并且新绘制的图像未绘制)。

这是我的代码:

from tkinter import *
from tkinter import filedialog
from PIL import Image, ImageTk

DARK_THEME      = "grey"
LIGHT_THEME     = "white"
THEME           = LIGHT_THEME


class Window():

    # object constructor
    def __init__(self, root, theme):

        # Sections #
        self.toolbar_frame = LabelFrame(root, bg=theme, height="40")
        self.toolbar_frame.pack(side=TOP, fill=X)

        # Canvas #
        self.draw_frame = Canvas(root)
        self.draw_frame.pack(side=RIGHT, fill=BOTH, expand=True)
        self.frame = self.draw_frame.create_image(0, 0, anchor=NW)

        # Buttons #
        self.source_button = Button(self.toolbar_frame, text="Source", bg=theme, command= lambda: self.load_static_source("./Sources/"))
        self.source_button.pack(side=LEFT)


    # Load image with tk compatibility
    def load_image(self, path_):

        print(path_)  ### DEBUG ###
        image = Image.open(path_)
        return ImageTk.PhotoImage(image)


    # Change canvas source with static one
    def load_static_source(self, dir_):

        path_ = filedialog.askopenfilename(initialdir = dir_, title = "Select file", filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
        self.draw_frame.itemconfig(self.frame, image=self.load_image(path_))



root = Tk()
Window(root, THEME)
root.mainloop()

我找到了另一篇关于此的文章,但我发现我所做的和给定的解决方案之间没有区别,这就是为什么我不明白为什么该代码无法正常工作的原因。

这是我找到的示例和相关帖子:

from Tkinter import *

#----------------------------------------------------------------------

class MainWindow():

    #----------------

    def __init__(self, main):

        # canvas for image
        self.canvas = Canvas(main, width=60, height=60)
        self.canvas.grid(row=0, column=0)

        # images
        self.my_images = []
        self.my_images.append(PhotoImage(file = "ball1.gif"))
        self.my_images.append(PhotoImage(file = "ball2.gif"))
        self.my_images.append(PhotoImage(file = "ball3.gif"))
        self.my_image_number = 0

        # set first image on canvas
        self.image_on_canvas = self.canvas.create_image(0, 0, anchor = NW, image = self.my_images[self.my_image_number])

        # button to change image
        self.button = Button(main, text="Change", command=self.onButton)
        self.button.grid(row=1, column=0)

    #----------------

    def onButton(self):

        # next image
        self.my_image_number += 1

        # return to first image
        if self.my_image_number == len(self.my_images):
            self.my_image_number = 0

        # change image
        self.canvas.itemconfig(self.image_on_canvas, image = self.my_images[self.my_image_number])

#----------------------------------------------------------------------

root = Tk()
MainWindow(root)
root.mainloop()

相关文章:stackoverflow topic

2 个答案:

答案 0 :(得分:1)

您需要保留对图像的引用。这是描述它的effbot页面的链接:https://effbot.org/tkinterbook/photoimage.htm

  

您必须在Python程序中保留对图像对象的引用,方法是将其存储在全局变量中,或者将其附加到另一个对象。

Xeyes编写的解决方案是正确的,并且此页进行了说明。

答案 1 :(得分:0)

所以我找到了解决方案。有点奇怪,但它可以工作。在将图像提供给canvas itemconfig方法之前,必须将其保存在class属性中。

现在看起来像:

var options = {
            "processing": true,
            "serverSide": true,
            "ajax": fullbase,
            "language": {
                "search": "Buscar: ",
                "zeroRecords": "Datos no encontrados."
            },
            "initComplete": function(settings, json) {
                $(".buttons-excel").click();
            },
            "iDisplayLength": 100000,
            lengthMenu: [[10,25,50,100, 100000], [10,25,50, 100, "All"]],
            "buttons": [{
                extend : 'excel',
                exportOptions : {
                        order : 'current',  
                        page : 'all',    
                        search : 'none' 
                }
            }],
            "dom": "Blfrtip",
        };

不仅仅是:

self.placeholder = self.load_image(path_)
self.draw_frame.itemconfig(self.frame, image=self.placeholder)