-1

我需要一种将图像作为窗口背景的方法,并且仍然能够在其上放置按钮和其他控件。

这是我的代码:

from __future__ import division
from Tkinter import *
from PIL import Image, ImageTk, ImageFilter
import random
import Tkinter as tk

class MyGame(object):




    def __init__(self):
        self.root=Tk()
        self.root.wm_title("Working Tittle")

        img = Image.open("azure.PNG").convert("L") # convert changes the color to grey etc
        (w, h) = (img.size[1], img.size[1])
        print (w, h)
        tkpi = ImageTk.PhotoImage(img)
        label = Label (self.root, image =tkpi)
        label.grid(row=0, column=0, padx=5, pady=5)
        img2 =img.copy()
        pixels = img2.load()
        for x in range(w):
            for y in range(h):
                pixels[x,y] = 255


        tkpi = ImageTk.PhotoImage(img)
        label = Label (self.root, image =tkpi)
        label.grid(row=0, column=0, padx=5, pady=5)







        #this is for the canvas
        self.canvas = Canvas(self.root, width=200, height=200,bg="blue")
        self.canvas.pack()
        self.rectangle = self.canvas.create_rectangle(1, 210,250, 130, fill='green', outline='green')
        self.rectangle = self.canvas.create_rectangle(100, 180, 160, 100, fill='grey', outline='grey')
        self.oval = self.canvas.create_oval(2,2,40,40, fill ='yellow', outline='yellow')
        points = [92, 101, 168, 101, 129, 77]
        self.polygon = self.canvas.create_polygon( points,fill ='brown', outline='brown')

        # used for the coordinates
        self.canvas.bind("<B1-Motion>",self.button_click)
        self.root.mainloop()

        # this is used to find the coordinate
    def button_click(self, e):
        self.canvas.coords(self.polygon, e.x, e.y)
        print "%d %d" %(e.x,e.y)




MyGame()
4

1 回答 1

2

我通常这样做的方式是 a) 使用您想要的背景图像创建一个标签,以及 b) 用于place将图像放置在包含框架中。这样做,您可以像往常一样继续在框架中打包或网格化对象。

例如:

self.image = tk.PhotoImage(...)
label = tk.Label(self,image=self.image)
label.place(x=0, y=0, relwidth=1.0, relheight=1.0, anchor="nw")
于 2012-11-01T17:35:40.677 回答