在画布上将图像制作为背景,TKinter

时间:2019-01-19 22:50:32

标签: python tkinter

我正在尝试将TKinter应用程序的背景用作图片。在将代码放入其方法和类之前,该代码可以正常工作。

import tkinter as tk
from tkinter import *
from PIL import ImageTk,Image

class simpleapp_tk(tk.Tk):
    def __init__(self,parent):
        tk.Tk.__init__(self,parent)
        self.parent = parent  #makes self.parent the parent
        self.Background()


    def Background(self):
        canvas = Canvas(self, width = 0, height = 0)
        canvas.pack(expand = YES, fill = BOTH)
        img = Image.open("watercoffee.jpg")
        photo = ImageTk.PhotoImage(img)
        canvas.create_image(0, 0, anchor=NW, image = photo)

if __name__ == "__main__":   #runs code
    app = simpleapp_tk(None)
    app.wm_geometry("625x390") # window size fed into app
    app.title('My Application')
    app.mainloop()

我想念什么?

1 个答案:

答案 0 :(得分:0)

请参阅以下经修改的代码中由##表示的我的评论。

import tkinter as tk
#from tkinter import * ## Why r u importing tkinter twice? Redundant.
from PIL import ImageTk,Image

class simpleapp_tk(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        #self.parent = parent  #makes self.parent the parent ## Tk is the top most widget, it does not have a parent/master
        self.Background()


    def Background(self):
        self.canvas = tk.Canvas(self, width=0, height=0) #Why use width=0 & height=0? Redundant.
        self.canvas.pack(expand='yes', fill='both')
        img = Image.open("watercoffee.jpg")
        self.photo = ImageTk.PhotoImage(img) ##images needs to be an attribute in a class. See 2nd comment in your question for explanation. 
        self.canvas.create_image(0, 0, anchor='nw', image=self.photo)  ##use self.photo

if __name__ == "__main__":   #runs code
    app = simpleapp_tk() ##removed None
    app.wm_geometry("625x390") # window size fed into app
    app.title('My Application')
    app.mainloop()