我需要一种方法将图像作为窗口的背景,并且仍然可以将按钮和其他控件放在其上。
这是我的代码:
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()
答案 0 :(得分:3)
我通常这样做的方法是: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")