473,748 Members | 11,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question for loading images in a class/canvas

31 New Member
I have been attempting to utilize a draw command script that loads a canvas, and through certain mouse events, draws rectangles. The original code is from http://www.java2s.com/Code/Python/Ev...peoncanvas.htm .

The code itself is:
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. trace = 0 
  3.  
  4. class CanvasEventsDemo: 
  5.     def __init__(self, parent=None):
  6.         canvas = Canvas(width=300, height=300, bg='beige') 
  7.         canvas.pack()
  8.         canvas.bind('<ButtonPress-1>', self.onStart)   
  9.         canvas.bind('<B1-Motion>',     self.onGrow)     
  10.         canvas.bind('<Double-1>',      self.onClear)     
  11.         canvas.bind('<ButtonPress-3>', self.onMove)     
  12.         self.canvas = canvas
  13.         self.drawn  = None
  14.         self.kinds = [canvas.create_oval, canvas.create_rectangle]
  15.     def onStart(self, event):
  16.         self.shape = self.kinds[0]
  17.         self.kinds = self.kinds[1:] + self.kinds[:1]      
  18.         self.start = event
  19.         self.drawn = None
  20.     def onGrow(self, event):                           
  21.         canvas = event.widget
  22.         if self.drawn: canvas.delete(self.drawn)
  23.         objectId = self.shape(self.start.x, self.start.y, event.x, event.y)
  24.         if trace: print objectId
  25.         self.drawn = objectId
  26.     def onClear(self, event):
  27.         event.widget.delete('all')                     
  28.     def onMove(self, event):
  29.         if self.drawn:                                   
  30.             if trace: print self.drawn
  31.             canvas = event.widget
  32.             diffX, diffY = (event.x - self.start.x), (event.y - self.start.y)
  33.             canvas.move(self.drawn, diffX, diffY)
  34.             self.start = event
  35.  
  36. if __name__ == '__main__':
  37.     CanvasEventsDemo()
  38.     mainloop()
Essentially I am looking at setting the background image as a photo using the create_image function. I have gotten it to work in a structure that is not utilizing classes such as this example code:
Expand|Select|Wrap|Line Numbers
  1. # Putting a gif image on a canvas with Tkinter
  2. # tested with Python24 by  vegaseat  25jun2005
  3.  
  4. from Tkinter import *
  5.  
  6. # create the canvas, size in pixels
  7. canvas = Canvas(width = 300, height = 200, bg = 'yellow')
  8.  
  9. # pack the canvas into a frame/form
  10. canvas.pack(expand = YES, fill = BOTH)
  11.  
  12. # load the .gif image file
  13. # put in your own gif file here, may need to add full path
  14. # like 'C:/WINDOWS/Help/Tours/WindowsMediaPlayer/Img/mplogo.gif'
  15. gif1 = PhotoImage(file = 'DrBunsen.gif')
  16.  
  17. # put gif image on canvas
  18. # pic's upper left corner (NW) on the canvas is at x=50 y=10
  19. canvas.create_image(50, 10, image = gif1, anchor = NW)
  20.  
  21. # run it ...
  22. mainloop()
I've gotten it to work with a different file of course, however, when I try to implement my image background in the first code all I get is a grey canvas. So without further ado here is my code:

Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. import Image            #PIL
  3. import ImageTk          #PIL
  4. import sys
  5. import getopt
  6. trace = 0 
  7.  
  8. class CanvasEventsDemo: 
  9.     def __init__(self, parent=NONE):
  10.         canvas = Canvas(width=400,height=400) 
  11.         canvas.pack()
  12.         im = Image.open("C:/Documents and Settings/John Perry/Desktop/GradSchool/Summer 07 python goshen/cd with CT's/patient10/se002.jpg")
  13.         photo = ImageTk.PhotoImage(im)
  14.         item=canvas.create_image(10, 10, image = photo)
  15.         canvas.bind('<ButtonPress-1>', self.onStart)   
  16.         canvas.bind('<B1-Motion>',     self.onGrow)     
  17.         canvas.bind('<Double-1>',      self.onClear)     
  18.         canvas.bind('<ButtonPress-3>', self.onMove)     
  19.         self.canvas = canvas
  20.         self.drawn  = None
  21.         self.kinds = [canvas.create_oval, canvas.create_rectangle]
  22.     def onStart(self, event):
  23.         self.shape = self.kinds[0]
  24.         self.kinds = self.kinds[1:] + self.kinds[:1]      
  25.         self.start = event
  26.         self.drawn = None
  27.     def onGrow(self, event):                           
  28.         canvas = event.widget
  29.         if self.drawn: canvas.delete(self.drawn)
  30.         objectId = self.shape(self.start.x, self.start.y, event.x, event.y)
  31.         if trace: print objectId
  32.         self.drawn = objectId
  33.     def onClear(self, event):
  34.         event.widget.delete('all')                     
  35.     def onMove(self, event):
  36.         if self.drawn:                                   
  37.             if trace: print self.drawn
  38.             canvas = event.widget
  39.             diffX, diffY = (event.x - self.start.x), (event.y - self.start.y)
  40.             canvas.move(self.drawn, diffX, diffY)
  41.             self.start = event
  42.  
  43. if __name__ == '__main__':
  44.     CanvasEventsDemo()
  45.     mainloop()
  46.  
Thanks for any help on getting this little issue fixed! Note that the section I'm referring to is around line 12. I just need my jpg or gif loaded as the background.

Thanks,
JP
Jun 22 '07 #1
6 3555
bartonc
6,596 Recognized Expert Expert
To fix line 12, use raw strings for Windows path names (because the "\" has a special purpose in python strings) and use the "\" in literal path names:
Expand|Select|Wrap|Line Numbers
  1. #
  2. # Use raw strings #
  3.         im = Image.open(r"C:\Documents and Settings\John Perry\Desktop\GradSchool\Summer 07 python goshen\cd with CT's\patient10\se002.jpg")
or
Expand|Select|Wrap|Line Numbers
  1. #
  2. # escape the backslash #
  3.         im = Image.open("C:\\Documents and Settings\\John Perry\\Desktop\\GradSchool\\Summer 07 python goshen\\cd with CT's\\patient10\\se002.jpg")
Jun 23 '07 #2
Nebulism
31 New Member
Hey all,

I implemented the raw string, however, the image will still not display on the canvas at all. It still remains as a white canvas bg with the mouse event functions. Any ideas, or can you try and get it to display an actual jpg, gif, etc image in the canvas to draw shapes over?

Thanks,
JP
Jun 23 '07 #3
bartonc
6,596 Recognized Expert Expert
Hey all,

I implemented the raw string, however, the image will still not display on the canvas at all. It still remains as a white canvas bg with the mouse event functions. Any ideas, or can you try and get it to display an actual jpg, gif, etc image in the canvas to draw shapes over?

Thanks,
JP
I'll try to get some time to work on this for you. I'm swamped at the moment.
Jun 23 '07 #4
bartonc
6,596 Recognized Expert Expert
I'll try to get some time to work on this for you. I'm swamped at the moment.
In the mean time, have you seen
An Introduction to Tkinter
?
Jun 23 '07 #5
Nebulism
31 New Member
I solved the issue. I had to reference my class correctly.

here is the fix:

Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. import Tkinter
  3. import Image            #PIL
  4. import ImageTk          #PIL
  5. import sys
  6. import getopt
  7. trace = 0 
  8.  
  9. class CanvasEventsDemo: 
  10.     def __init__(self, parent=NONE):
  11.         canvas = Canvas(win)
  12.         canvas.pack(fill=BOTH)
  13.         self.img = PhotoImage(file="C:/Documents and Settings/John Perry/Desktop/GradSchool/Summer 07 python goshen/cd with CT's/patient10/se002.gif")
  14.         canvas.config(width=self.img.width(), height=self.img.height())
  15.         canvas.create_image(0,0, image=self.img, anchor=NW)
  16.         canvas.bind('<ButtonPress-1>', self.onStart)   
  17.         canvas.bind('<B1-Motion>',     self.onGrow)     
  18.         canvas.bind('<Double-1>',      self.onClear)     
  19.         canvas.bind('<ButtonPress-3>', self.onMove)     
  20.         self.canvas = canvas
  21.         self.drawn  = None
  22.         self.kinds = [canvas.create_rectangle]
  23.     def onStart(self, event):
  24.         event.widget.delete('all')
  25.         self.canvas.create_image(0,0, image=self.img, anchor=NW)
  26.         self.shape = self.kinds[0]
  27.         self.kinds = self.kinds[1:] + self.kinds[:1]      
  28.         self.start = event
  29.         self.drawn = None
  30.     def onGrow(self, event):                           
  31.         canvas = event.widget
  32.         if self.drawn: canvas.delete(self.drawn)
  33.         objectId = self.shape(self.start.x, self.start.y, event.x, event.y)
  34.         if trace: print objectId
  35.         self.drawn = objectId
  36.         self.xorig=self.start.x
  37.         self.yorig=self.start.y
  38.         self.xfinal=event.x
  39.         self.yfinal=event.y
  40.     def onClear(self, event):
  41.         event.widget.delete('all')
  42.         self.canvas.create_image(0,0, image=self.img, anchor=NW)
  43.     def onMove(self, event):
  44.         if self.drawn:                                   
  45.             if trace: print self.drawn
  46.             canvas = event.widget
  47.             diffX, diffY = (event.x - self.start.x), (event.y - self.start.y)
  48.             canvas.move(self.drawn, diffX, diffY)
  49.             self.start = event
  50.  
  51. if __name__ == '__main__':
  52.     win=Tk()
  53.     jop=CanvasEventsDemo()
  54.     mainloop()
JP
Jun 23 '07 #6
bartonc
6,596 Recognized Expert Expert
Awesome! Thanks for keeping us up-to-date with you progress.
Jun 23 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

2
2373
by: Tim Flynn | last post by:
Hi, I'm trying to write a simple image viewer using Tkinter and ImageTk from the PIL toolkit. The images are stored in memory and I don't want to create temporary files for them. My code looks like this : from Tkinter import *
17
4811
by: Aguilar, James | last post by:
My previous example used the concept of a Shape class heirarchy, so I will continue with that. Suppose I have something like fifty different shapes, and I am trying to instantiate one of them. The trick is, the instatiation will be based on a string with the exact same name as the type that I am trying to instantiate. Obviously, writing a fifty element long switch statement is an inferior solution. So, how can I instantiate based on...
2
3031
by: Kamran | last post by:
Hi I have very little experience of C++, nevertheless I have been asked to write a gui using QT/QWT. I know that I should direct the question to the relevant mailing list and I have done that but I think my problem has to do with my lack of understandign of some issues in C++. There is a class in QWT called QwtPicker which allows one to make rubberbands and select part of the drawing canvas, very useful in zooming etc. Function...
1
15901
by: namratapatil | last post by:
Hi...i am trying to load an image that has been saved at the following path: C:\WTK22\apps\MyProject\res After exectuing the program, the NullPointerException is thrown...Kindly let me know how to load the image without any exceptions being thrown... import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class ImmutableImageExample extends MIDlet { private Display display; private MyCanvas canvas;
0
1490
by: Eric_Dexter | last post by:
I know this might be the wrong place to ask but I recently modified the ogl example from wxpython and it works fine in spe but when I call it from other programs it wierds out because of the run.py thing they have set it up with doesn't work when I call it from an external program (including .bat files). when I call it outside of spe I manage to just get a box without the tracker part. It is so close to out right theft I was hopeing I...
3
2466
by: Nebulism | last post by:
Hi everyone! Earlier I asked a question about mouse interaction with a GUI. I have found a pretty comprehensive script that is supposed to work <mod edit: link removed, source inserted>:# This class describes a generic method of drawing rubberbands # on a wxPython canvas object (wxStaticBitmap, wxPanel etc) when # the user presses the left mouse button and drags it over a rectangular # area. It has methods to return the selected area by...
3
4975
by: Nebulism | last post by:
Hi everyone, I am working on a module for my GUI that shows one image with an index value below and would use a scrollbar to control which of the images are displayed. The images are stored in a successive folder in the format Pic#, i,e. Pic1, Pic2 etc. What I want to do is make a slider that is attached to a label which would output the slide number that is being looked at. I would use that number then to return the image of the slide...
10
7368
by: blaine | last post by:
Hey everyone! I'm not very good with Tk, and I am using a very simple canvas to draw some pictures (this relates to that nokia screen emulator I had a post about a few days ago). Anyway, all is well, except one thing. When I am not in the program, and the program receives a draw command (from a FIFO pipe), the canvas does not refresh until I click into the program. How do I force it to refresh, or force the window to gain focus? It...
3
2983
by: joshdw4 | last post by:
I hate to do this, but I've thoroughly exhausted google search. Yes, it's that pesky root window and I have tried withdraw to no avail. I'm assuming this is because of the methods I'm using. I guess my question is two-fold. 1) How do I get rid of that window? 2) Any comments in general? I am just learning python (and coding with classes), so I'm sure there are things I should pound into my head before I learn bad habits. Here's the...
0
8989
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9537
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9367
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9243
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8241
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6795
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4599
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2213
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.