如何在tkinter上放置图像

时间:2019-04-14 01:50:48

标签: tkinter tkinter-canvas

我无法在图形界面之一的页面上显示图片

from tkinter import *
from tkinter import ttk

LARGE_FONT= ("Verdana", 20)

class MyApp(Tk):

    def __init__(self):
        Tk.__init__(self)
        container = ttk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        self.frames = {}
        for F in (PageOne, PageTwo):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky = NSEW)
        self.show_frame(PageOne)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

    def get_page(self, classname):
        '''Returns an instance of a page given it's class name as a string'''
        for page in self.frames.values():
            if str(page.__class__.__name__) == classname:
                return page
        return None  

我想将图像放在PAGEONE上,但是画布没有属性。这是否意味着我无法使用它? 我删除了Pagetwo,以便我的代码更小且不占用空间

class PageOne(ttk.Frame):
    def __init__(self, parent, controller):
        ttk.Frame.__init__(self, parent)
        ttk.Label(self, text='Home Page', font=LARGE_FONT).grid(padx=(400,400), pady=(50,50))
        self.controller = controller
        self.make_widget(controller)

# Image 
        canvas = ttk.Canvas(self, width = 1000, height = 1000)
        canvas.grid()
        image = self.Image(file="mypicture.png")
        canvas.create_image(480, 258, image = image, anchor = ttk.NW)

    def make_widget(self, controller):
        self.v = StringVar()
        self.v.set("a")

        button1 = ttk.Button(self, text="Dispensing", command=self.validate)
        button1.grid(padx=20, pady=30)

        button2 = ttk.Button(self, text='Settings',
                              command=lambda: controller.show_frame(PageTwo))
        button2.grid(padx=20, pady=20)        

    def validate(self):
       value = self.v.get()
       if value == "a":
           print("Small Amount Dispensing")

app = MyApp()
app.title('Multi-Page Test App')
app.mainloop()

1 个答案:

答案 0 :(得分:0)

您可以在函数内部创建图像,当函数结束时,将对该图像的引用进行垃圾收集。您必须保存对图像的引用。检查以下代码:

# Image
canvas = Canvas(self, width = 1000, height = 1000)
canvas.grid()
image = PhotoImage(file="mypicture.png")
canvas.create_image(480, 258, image=image, anchor=NW)
canvas.image = image    # Save a reference to the image

据我所知,没有ttk.Canvas小部件;使用tkinter小部件。与ttk.NW相同。

创建图像的功能是PhotoImage