Image not getting drawn on tkinter canvas - python

I would like to display a knapsack image on green canvas. The height and width of that canvas is 250X250 pixels.
And the size of the image is 260X280 pixels.
When I try to execute below code, I get the output as shown in screenshot above 1. The location of the code file and image file is same.
from tkinter.font import BOLD
from tkinter import *
import tkinter
from PIL import Image, ImageTk
root = Tk()
def draw():
global canvas
root.geometry('1080x720')
root.state('zoomed')
canvas = Canvas(root,bg='black',highlightthickness=0)
canvas.pack(fill=tkinter.BOTH, expand=True)
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
canvas.create_line(int(sw*0.0000),int(sh*0.1736),int(sw*0.6510),int(sh*0.1736),fill='white')
canvas.create_line(int(sw*0.6510),int(sh*0.0000),int(sw*0.6510),int(sh*1.0000),fill='white')
canvas.create_line(int(sw*0.6510),int(sh*0.1157),int(sw*1.0000),int(sh*0.1157),fill='white')
canvas.create_line(int(sw*0.6510),int(sh*0.8101),int(sw*1.0000),int(sh*0.8101),fill='white')
UI_frame1 = Frame(canvas,bg='black',width=int(sw*0.6510),height=int(sh*0.1580))
canvas.create_window(0,0, anchor=NW,window=UI_frame1)
N = Label(UI_frame1,text='N',bg ='black',fg='white',font=(12))
N.grid(row=0,column=0, padx=139,pady=22)
weights = Label(UI_frame1,text='Weights',bg ='black',fg='white',font=(12))
weights.grid(row=0,column=1,padx=140,pady=22)
val = Label(UI_frame1,text='Values',bg ='black',fg='white',font=(12))
val.grid(row=0,column=2,padx=140,pady=22)
n = Entry(UI_frame1,bg='white',width=4,font=(12))
n.grid(row=1,column=0,padx=50,pady=17)
value_arr = Entry(UI_frame1,bg='white',font=(12))
value_arr.grid(row=1,column=1,padx=50,pady=17)
weight_arr = Entry(UI_frame1,bg='white',font=(12))
weight_arr.grid(row=1,column=2,padx=50,pady=17)
Label(canvas,text='i',bg='black',fg='white',font=(14)).place(x=150,y=185)
i = Label(canvas,text=" i ",bg='white',font=(12)).place(x=175,y=185)
Label(canvas,text='j',bg='black',fg='white',font=(14)).place(x=525,y=185)
j = Label(canvas,text=" j ",bg='white',font=(12)).place(x=550,y=185)
table = Canvas(canvas,bg='red',width=600,height=450)
table.place(x=75,y=300)
w = int(600/8)
h = int(450/5)
x=0
y=0
for r in range(5):
for c in range(8):
table.create_rectangle(x,y,x+w,y+h)
x+=w
y+=h
x=0
UI_frame2 = Frame(canvas,bg='blue',width=250,height=250)
canvas.create_window(835,630, anchor=CENTER,window=UI_frame2)
image_c = Canvas(UI_frame2,bg='green',highlightthickness=0,width=250,height=250)
image_c.grid(row=0,column=0,padx=0,pady=0)
photo = ImageTk.PhotoImage(file ='knapsack.png')
image_c.create_image(835,630,image=photo,anchor=NW)
draw()
root.mainloop()
I would like to cover the entire green canvas with single image of knapsack. I am not any error while running the GUI. Anyone could help me out, I'll be really thankful.

There are two problems:
First:
You display in position (835,630) but canvas has visible only (250, 250) - (top left corner is (0,0)) - so photo is in place which you can see.
Second:
There is bug in PhotoImage() which removes image from memory when it is assigned to local variable. One of solution is to use global photo to assign it to global variable.
def draw():
global canvas
global photo # use global variable
#... code ...
photo = ImageTk.PhotoImage(file='knapsack.png')
image_c.create_image(0, 0,image=photo, anchor=NW) # position (0,0)
Doc (on archive.org): PhotoImage - see Note at the botton of doc.
Other problem can be that image has big (transparent) margins around object and it may show object in differnt place then you may expect.
Screenshot shows photo in position (0,0) but object is in center of green canvas.

Related

How do I make collision objects in python tkinter?

I'm making a 2D game where I need objects to scroll up the screen while the player avoids the objects. I need the game to end when the player hits the objects.
it should look something like this:
So far I can move the skier(image) left and right:
import tkinter
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.geometry("800x600")
#canvas dimensions
w = 800
h = 1000
x = w/2
y = h/2
#canvas
my_canvas = Canvas(root, width=w, height=h, bg="white")
my_canvas.pack(pady=20)
#import player image
img=Image.open(r"C:/Users/Gebruiker/Pictures/player.png")
resized = img.resize((300,225), Image.ANTIALIAS)
new_img = ImageTk.PhotoImage(resized)
new_image = my_canvas.create_image(150,100, anchor=NW,image = new_img)
#player movement
def left(event):
x = -20
y = 0
my_canvas.move(new_image,x,y)
def right(event):
x = 20
y = 0
my_canvas.move(new_image,x,y)
root.bind("<Left>", left)
root.bind("<Right>", right)
How do I randomly spawn objects at regular intervals? I think I need some function to scroll the canvas as the objects spawn.
Similar posts usually had 1 object moving in a changing direction. However, I need lots of objects to spawn continuously.
Also, how do I make a collision border to stop the player going off the canvas?

Image in Button tkinter

I am having a problem in making a login image to a button. I have succeeded in making the image with a transparent background, but I can't succeed to make the button with transparent background.
I attached a screenshot that shows what I mean. The upper 'login' is a image (with transparent background), the lower is Login button but there is a white background around it. I want to make a button with transparent background.
self.login_image = Image.open('images/LoginButton.png')
self.login_image = ImageTk.PhotoImage(self.login_image)
self.main_screen_canvas.create_image(700, 300, image=self.login_image)
self.login_button = Button(self.main_screen_canvas, borderwidth=0, image=self.login_image)
self.login_button.place(x=300,y=400)
What should I do?
BackgroundImage
LoginButtonImage
Here's how to do what I was suggesting in the comment which uses the technique shown in another answer of mine to simulate a tkinter Button on a Canvas that has a transparent image placed on it (instead of text).
One issue I ran into was that fact that your 2421 × 1210 pixel background image was larger than my screen. To deal with it I added a fitrect() helper function to determine a new smaller size for it that would fit. I wrote it a long time ago, but have found it handy to have around many times (like now). Note that in the code ll and ur refer to the lower-left and upper-right corners of the rectangles involved.
Here's the resulting code:
from PIL import Image, ImageTk
import tkinter as tk
class CanvasButton:
""" Create left mouse button clickable canvas image object.
The x, y coordinates are relative to the top-left corner of the canvas.
"""
flash_delay = 100 # Milliseconds.
def __init__(self, canvas, x, y, image_source, command, state=tk.NORMAL):
self.canvas = canvas
if isinstance(image_source, str):
self.btn_image = tk.PhotoImage(file=image_source)
else:
self.btn_image = image_source
self.canvas_btn_img_obj = canvas.create_image(x, y, anchor='nw', state=state,
image=self.btn_image)
canvas.tag_bind(self.canvas_btn_img_obj, "<ButtonRelease-1>",
lambda event: (self.flash(), command()))
def flash(self):
self.set_state(tk.HIDDEN)
self.canvas.after(self.flash_delay, self.set_state, tk.NORMAL)
def set_state(self, state):
""" Change canvas button image's state.
Normally, image objects are created in state tk.NORMAL. Use value
tk.DISABLED to make it unresponsive to the mouse, or use tk.HIDDEN to
make it invisible.
"""
self.canvas.itemconfigure(self.canvas_btn_img_obj, state=state)
def fitrect(r1_ll_x, r1_ll_y, r1_ur_x, r1_ur_y, r2_ll_x, r2_ll_y, r2_ur_x, r2_ur_y):
""" Find the largest rectangle that will fit within rectangle r2 that has
rectangle r1's aspect ratio.
Note: Either the width or height of the resulting rect will be
identical to the corresponding dimension of rect r2.
"""
# Calculate aspect ratios of rects r1 and r2.
deltax1, deltay1 = (r1_ur_x - r1_ll_x), (r1_ur_y - r1_ll_y)
deltax2, deltay2 = (r2_ur_x - r2_ll_x), (r2_ur_y - r2_ll_y)
aspect1, aspect2 = (deltay1 / deltax1), (deltay2 / deltax2)
# Compute size of resulting rect depending on which aspect ratio is bigger.
if aspect1 > aspect2:
result_ll_y, result_ur_y = r2_ll_y, r2_ur_y
delta = deltay2 / aspect1
result_ll_x = r2_ll_x + (deltax2 - delta) / 2.0
result_ur_x = result_ll_x + delta
else:
result_ll_x, result_ur_x = r2_ll_x, r2_ur_x
delta = deltax2 * aspect1
result_ll_y = r2_ll_y + (deltay2 - delta) / 2.0
result_ur_y = result_ll_y + delta
return result_ll_x, result_ll_y, result_ur_x, result_ur_y
def btn_clicked():
""" Prints to console a message every time the button is clicked """
print("Button Clicked")
background_image_path = 'background_image.jpg'
button_image_path = 'button_image.png'
root = tk.Tk()
root.update_idletasks()
background_img = Image.open(background_image_path) # Must use PIL for JPG images.
scrnwidth, scrnheight = root.winfo_screenwidth(), root.winfo_screenheight()
bgrdwidth, bgrdheight = background_img.size
border_width, border_height = 20, 20 # Allow room for window's decorations.
# Determine a background image size that will fit on screen with a border.
bgr_ll_x, bgr_ll_y, bgr_ur_x, bgr_ur_y = fitrect(
0, 0, bgrdwidth, bgrdheight,
0, 0, scrnwidth-border_width, scrnheight-border_height)
bgr_width, bgr_height = int(bgr_ur_x-bgr_ll_x), int(bgr_ur_y-bgr_ll_y)
# Resize background image to calculated size.
background_img = ImageTk.PhotoImage(background_img.resize((bgr_width, bgr_height)))
# Create Canvas same size as fitted background image.
canvas = tk.Canvas(root, bd=0, highlightthickness=0, width=bgr_width, height=bgr_height)
canvas.pack(fill=tk.BOTH)
# Put background image on Canvas.
background = canvas.create_image(0, 0, anchor='nw', image=background_img)
# Put CanvasButton on Canvas centered at the bottom.
button_img = tk.PhotoImage(file=button_image_path)
btn_x, btn_y = (bgr_width/2), (bgr_height-button_img.height())
canvas_btn1 = CanvasButton(canvas, btn_x, btn_y, button_img, btn_clicked)
root.mainloop()
And here's the result of running it:

Add lable, textbox and button to tkinter canvas

How to add a label, textbox and button to a program in which an image is display using tkinter canvas. In this program, an image is displayed to user. Lines are drawn over image on mouse click at different position. I want to add a textbox and a button, so that user can enter name for the object drawn using mouse clicks. For example, Enter label: textboxforinputname__Button to enter.
from Tkinter import *
import Image, ImageTk, ImageDraw
import numpy as np
coord=[] # for saving coord of each click position
Dict_Polygon={} # Dictionary for saving polygon
list_of_points=[]
flag=True
label=0
def draw_lines(event):
mouse_xy = (event.x, event.y)
func_Draw_lines(mouse_xy)
def func_Draw_lines(mouse_xy):
center_x, center_y = mouse_xy
if canvas.old_coords:
x1, y1 = canvas.old_coords
canvas.create_line(center_x, center_y, x1, y1)
# add clicked positions to list
if flag==True:
list_of_points.append(mouse_xy)
canvas.old_coords = center_x, center_y
# Main function
if __name__ == '__main__':
root = Tk()
# Input image
img = Image.open("test.jpg")
# Draw canvas for iput image to pop up image for clicks
filename = ImageTk.PhotoImage(img)
canvas = Canvas(root,height=img.size[0],width=img.size[0])
canvas.image = filename
canvas.create_image(0,0,anchor='nw',image=filename)
canvas.pack()
canvas.old_coords = None
# bind function to canvas to generate event
canvas.bind("<Button 3>", draw_lines)
root.mainloop()

Copy Tkinter Canvas Items

I need top be able to create a copy of a tkinter canvas item, so that a copy of an image can be dragged off of an original. I have dragging working for the images, but I cannot seem to copy the image item. Any help would be greatly appreciated! Thanks.
EDIT: Sorry for not including my code at first. I was able to solve the problem thanks to the answer that was given. Here's a trimmed down example of my code that now works:
from tkinter import *
from PIL import Image, ImageTk
def OnBaseButtonPress(event):
#record the item and its location
drag_data["item"] = c.find_closest(event.x, event.y)
i = c.itemcget(drag_data["item"], "image") #finds the image source of the object
refs.append(i) #keep a reference!
c.create_image(c.coords(drag_data["item"]), image=i, tags="base") #creates an identical object at the position
drag_data["x"] = event.x
drag_data["y"] = event.y
def OnBaseButtonRelease(event):
#reset drag info
drag_data["item"] = None
drag_data["x"] = 0
drag_data["y"] = 0
def OnBaseMotion(event):
#calculate how far the item has moved
delta_x = event.x - drag_data["x"]
delta_y = event.y - drag_data["y"]
#move the object that amount
c.move(drag_data["item"], delta_x, delta_y)
#record the new position
drag_data["x"] = event.x
drag_data["y"] = event.y
#set up canvas and image
root = Tk()
c = Canvas(root, width=800, height=600)
c.pack()
test = ImageTk.PhotoImage(Image.open("test.png"))
c.create_image(400, 300, image=test, tags="base")
refs=[] #used to keep references to images used in functions
#bind mouse keys
c.tag_bind("base", "<ButtonPress-1>", OnBaseButtonPress)
c.tag_bind("base", "<ButtonRelease-1>", OnBaseButtonRelease)
c.tag_bind("base", "<B1-Motion>", OnBaseMotion)
drag_data={"x": 0, "y": 0, "item": None}
mainloop()
You can get item type canvas.type(item), item configuration canvas.itemconfig(item), and etc.
And then you can recreate an identical object.
See also: Tkinter - making a second canvas display the contents of another.

How can I convert canvas content to an image?

from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()
I want to convert canvas content to a bitmap or other image, and then do other operations, such as rotating or scaling the image, or changing its coordinates.
Bitmaps can improve efficiency to show if I am no longer drawing.
What should I do?
You can either generate a postscript document (to feed into some other tool: ImageMagick, Ghostscript, etc):
from Tkinter import *
root = Tk()
cv = Canvas(root)
cv.create_rectangle(10,10,50,50)
cv.pack()
root.mainloop()
cv.update()
cv.postscript(file="file_name.ps", colormode='color')
root.mainloop()
or draw the same image in parallel on PIL and on Tkinter's canvas (see: Saving a Tkinter Canvas Drawing (Python)). For example (inspired by the same article):
from Tkinter import *
import Image, ImageDraw
width = 400
height = 300
center = height//2
white = (255, 255, 255)
green = (0,128,0)
root = Tk()
# Tkinter create a canvas to draw on
cv = Canvas(root, width=width, height=height, bg='white')
cv.pack()
# PIL create an empty image and draw object to draw on
# memory only, not visible
image1 = Image.new("RGB", (width, height), white)
draw = ImageDraw.Draw(image1)
# do the Tkinter canvas drawings (visible)
cv.create_line([0, center, width, center], fill='green')
# do the PIL image/draw (in memory) drawings
draw.line([0, center, width, center], green)
# PIL image can be saved as .png .jpg .gif or .bmp file (among others)
filename = "my_drawing.jpg"
image1.save(filename)
root.mainloop()
I have found a great way of doing this which is really helpful. For it, you need the PIL module. Here is the code:
from PIL import ImageGrab
def getter(widget):
x=root.winfo_rootx()+widget.winfo_x()
y=root.winfo_rooty()+widget.winfo_y()
x1=x+widget.winfo_width()
y1=y+widget.winfo_height()
ImageGrab.grab().crop((x,y,x1,y1)).save("file path here")
What this does is you pass a widget name into the function. The command root.winfo_rootx() and the root.winfo_rooty() get the pixel position of the top left of the overall root window.
Then, the widget.winfo_x() and widget.winfo_y() are added to, basically just get the pixel coordinate of the top left hand pixel of the widget which you want to capture (at pixels (x,y) of your screen).
I then find the (x1,y1) which is the bottom left pixel of the widget. The ImageGrab.grab() makes a printscreen, and I then crop it to only get the bit containing the widget. Although not perfect, and won't make the best possible image, this is a great tool for just getting a image of any widget and saving it.
If you have any questions, post a comment! Hope this helped!
Use Pillow to convert from Postscript to PNG
from PIL import Image
def save_as_png(canvas,fileName):
# save postscipt image
canvas.postscript(file = fileName + '.eps')
# use PIL to convert to PNG
img = Image.open(fileName + '.eps')
img.save(fileName + '.png', 'png')
Maybe you can try to use widget_winfo_id to get the HWND of the canvas.
import win32gui
from PIL import ImageGrab
HWND = canvas.winfo_id() # get the handle of the canvas
rect = win32gui.GetWindowRect(HWND) # get the coordinate of the canvas
im = ImageGrab.grab(rect) # get image of the current location
A better way for #B.Jenkins's answer that doesn't need a reference to the root object:
from PIL import ImageGrab
def save_widget_as_image(widget, file_name):
ImageGrab.grab(bbox=(
widget.winfo_rootx(),
widget.winfo_rooty(),
widget.winfo_rootx() + widget.winfo_width(),
widget.winfo_rooty() + widget.winfo_height()
)).save(file_name)
On my system had serious issues with ghostscript and the ImageGrab in general. Solution draw on PIL Image, save as a file, load file on PhotoImage, which is used to create new TKinter Canvas.
canvas = Canvas(win, width=IMG_W, height=IMG_H)
img = PILImg.new("RGB", (IMG_W, IMG_H), "#000")
draw = ImageDraw.Draw(img)
draw.rectangle([x,y,w,h], fill=color, outline=border)
img.save("stock-chart.png")
copyImg = PhotoImage(file="stock-chart.png")
canvas.create_image(IMG_W_2, IMG_H_2, image=copyImg)

Categories