wxpython: How to add am image in text control - python

Am trying to display image in text control but it display only binary characters.
But is their any way I can archive this or its impossible dream to do it in wxpython
Please help I will need this agently.
Thank you advance
Here are the source codes that I have so far
import wx
class MainFrame(wx.Frame):
def __init__(self,*args,**kwargs):
super(MainFrame,self).__init__(*args,**kwargs)
self.main_panel = MainPanel(self,-1)
class MainPanel(wx.Panel):
def __init__(self,*args,**kwargs):
super(MainPanel,self).__init__(*args,**kwargs)
img1 = wx.Image("coins.png", wx.BITMAP_TYPE_ANY)
w = img1.GetWidth()
h = img1.GetHeight()
img1 = img1.Scale(w/2, h/2)
sb1 = wx.StaticBitmap(self, -1, wx.BitmapFromImage(img1))
self.txtctrl = wx.TextCtrl(self,-1,"display image here",size=(500,300),pos=(20,10))
class App(wx.App):
def OnInit(self):
mainframe = MainFrame(None,-1,title="Display image in txt ctrl",size=(600,400))
mainframe.Show()
mainframe.Center()
return True
if __name__ == "__main__":
app = App();
app.MainLoop()

You cannot put an image directly inside a regular wx.TextCtrl widget. That is currently impossible as they just don't support that. However, you can put an image into a RichTextCtrl widget. If you haven't downloaded it yet, be sure to get the wxPython demo from the project's website as it has a good example. Here are a couple links:
http://wxpython.org/Phoenix/docs/html/richtext.RichTextCtrl.html
http://play.pixelblaster.ro/blog/archive/2008/10/08/richtext-control-with-wxpython-saving-and-loading
If you just want to put an image in your application, then wx.Image is your friend (as John already mentioned).

You can do it with wx.Image read this
you can also see a more complex example here

Related

Troubles uploading images in tkinter [duplicate]

I am a newbie to python.I have a code where the image is not printed on the Tkinter.So please help me on how to display the image along with the Button and Textbox.
Code:
import Tkinter
from Tkinter import *
class myproject(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self)
self.button2()
self.text()
self.image()
def button2(self):
button2 = Tkinter.Button(self, text = "hello")
button2.grid(column=5,row=7)
def text(self):
text = Tkinter.Text(self, height=3, width=31) # self.text
text.grid(column=1,row=3)
text.insert(END, "Wiilliam Skakespeare")
def image(self):
logo = PhotoImage(file="linux.gif")
w1 = Tkinter.Label(self, image=logo).pack(side="right")
app = myproject(None)
app.mainloop()
Please help!Answers will be appreciated!
You have to save a reference to the photo image.
See this page for more information, or this one
There are numerous other problems with the code you posted, however; you need colons after function and class declarations, for example. When posting code, there's also no need for extraneous methods in the class, they only make it more difficult to understand
You also cannot mix managers or you're whole program might stall. This means you shouldn't be using pack and grid in the same program. Read through the effbot tutorial, it's really helpful!
class myproject(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self)
self.image()
def image(self):
logo = Tkinter.PhotoImage(file='linux.gif')
self.logo = logo # You always need a reference to the image or it gets garbage collected
w1 = Tkinter.Label(self, image=logo).grid()
app = myproject(None)
app.mainloop()

Python: Tkinter not displaying my image or UI

I am trying to create a user interface with a picture in its top right corner. Here is my code:
import tkinter as tk
import urllib.request
import base64 as b64
class my_ui(tk.Tk):
def __init__(self, parent):
tk.Tk.__init__(self,parent)
self.parent=parent
self.intialize()
def intialize(self):
self.grid()
#Welcome
label = tk.Label(self,text="Welcome to my UI", anchor='center',fg='white',bg='blue')
label.grid(column=0,row=0,columnspan=2,rowspan=2,sticky='EW')
#Buttons
button = tk.Button(self,text="Button 1",command=self.OnButtonClick)
button.grid(column=0,row=3,sticky='W')
def OnButtonClick(self):
print("You clicked the button!")
if __name__ == "__main__":
app = my_ui(None)
#Logo URL - just a smiley face
URL = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQCItlNQe0QaiuhkADUwgVTpx-Isaym6RAP06PHkzBe2Yza3a4rYIkHuB8"
u = urllib.request.urlopen(URL)
raw_data = u.read()
u.close()
b64_data = b64.encodestring(raw_data)
photo = tk.PhotoImage(data=b64_data)
logo = tk.Label(app, image=photo)
logo.image = photo # To save it in memory
logo.pack() # If I exclude this line, UI works fine.
app.title('My User Interface')
app.mainloop()
I am pulling a .gif from the web and returning a PhotoImage with my function. When I run this, I get no errors - rather, my tkinter window does not appear whatsoever. When I take out the line I mentioned in the comment, my UI comes up fine (buttons, but no image) with no errors.
I am unsure of what exactly the absence of the window means. I am running Python 3.4.1 on Mac OSx. Any help would be greatly appreciated!
When a tk.PhotoImage object gets garbage collected, the image is "released", so to speak. The image is still technically being used, so it's not destroyed, but it will get completely blanked out. Replace your return line with:
photo = tk.PhotoImage(data=b64_data)
return photo
Just be sure to declare photo as a global variable.

pygtk how to update gtk.Image

I have very strange problem with gtk.Image(). Simple question; how to update image?
On window creation I create image and pack it… On that time I load image from disk. Now I start downloading image from url, and when it's done I just want to replace existing image with new one. I rewrite content of same file on disk and then do:
pixbuf = gtk.gdk.pixbuf_new_from_file(image_path)
self._user_avatar.set_from_pixbuf(pixbuf)
I have tried
self._user_avatar.set_from_file(image_path)
and
self._user_avatar.clear()
nothing works. When i restart app there is a new image and everything is ok.
gtk.Image.set_from_pixbuf is the right method, so your problem may come from something else. Try on the most simple piece of code to reproduce your problem.
Here's a working sample:
import pygtk
pygtk.require('2.0')
import gtk
pics = []
clicks = 0
def on_destroy (widget):
gtk.main_quit()
return False
def on_button_clicked (widget, image):
global clicks
clicks += 1
image.set_from_pixbuf (pics[clicks % len(pics)])
def create ():
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect("destroy", on_destroy)
pics.append (gtk.gdk.pixbuf_new_from_file("sample1.png"))
pics.append (gtk.gdk.pixbuf_new_from_file("sample2.png"))
image = gtk.Image()
image.set_from_pixbuf(pics[0])
button = gtk.Button ("Switch Image")
button.connect("clicked", on_button_clicked, image)
vbox = gtk.VBox()
vbox.pack_start (image)
vbox.pack_start (button)
window.add(vbox)
window.show_all()
if __name__ == "__main__":
create()
gtk.main()

wx.Media video load ....Video file not playing

I want to start playing a .wmv file as soon as it is loaded in wxPython. I wrote a small code for it. The code does not give any error, but it does not show any video as well, but the sound does play in the background. It just shows a gray screen. Following is the code I wrote for my program.
import wx
import wx.media
class TestPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1, style=wx.TAB_TRAVERSAL|wx.CLIP_CHILDREN)
# Create some controls
try:
self.mc = wx.media.MediaCtrl(self, style=wx.SIMPLE_BORDER)
except NotImplementedError:
self.Destroy()
raise
self.mc.Load(r"C:\Documents and Settings\N1002401B\Desktop\test1.wmv")
#self.slider.SetRange(0, self.mc.Length())
#folder, filename = os.path.split("C:\Documents and Settings\N1002401B\Desktop\test1.wmv")
self.Bind(wx.media.EVT_MEDIA_LOADED, self.OnPlay)
def OnPlay(self,evt):
self.mc.Play()
app = wx.App(0)
frame = wx.Frame(None)
panel = TestPanel(frame)
frame.Show()
app.MainLoop()
I am using Python 2.7 and windows XP.
Can anyone please help me on this one. I would be really grateful for your help.

Showing an image from console in Python

What is the easiest way to show a .jpg or .gif image from Python console?
I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-up graphical windows?
Using the awesome Pillow library:
>>> from PIL import Image
>>> img = Image.open('test.png')
>>> img.show()
This will open the image in your default image viewer.
In a new window using Pillow/PIL
Install Pillow (or PIL), e.g.:
$ pip install pillow
Now you can
from PIL import Image
with Image.open('path/to/file.jpg') as img:
img.show()
Using native apps
Other common alternatives include running xdg-open or starting the browser with the image path:
import webbrowser
webbrowser.open('path/to/file.jpg')
Inline a Linux console
If you really want to show the image inline in the console and not as a new window, you may do that but only in a Linux console using fbi see ask Ubuntu or else use ASCII-art like CACA.
Since you are probably running Windows (from looking at your tags), this would be the easiest way to open and show an image file from the console without installing extra stuff like PIL.
import os
os.system('start pic.png')
Or simply execute the image through the shell, as in
import subprocess
subprocess.call([ fname ], shell=True)
and whatever program is installed to handle images will be launched.
In Xterm-compatible terminals, you can show the image directly in the terminal. See my answer to "PPM image to ASCII art in Python"
If you would like to show it in a new window, you could use Tkinter + PIL library, like so:
import tkinter as tk
from PIL import ImageTk, Image
def show_imge(path):
image_window = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(image_window, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
image_window.mainloop()
This is a modified example that can be found all over the web.
Why not just display it in the user's web browser?
You cannot display images in a console window.
You need a graphical toolkit such as Tkinter, PyGTK, PyQt, PyKDE, wxPython, PyObjC, or PyFLTK.
There are plenty of tutorials on how to create simple windows and loading images in python.
You can also using the Python module Ipython, which in addition to displaying an image in the Spyder console can embed images in Jupyter notebook. In Spyder, the image will be displayed in full size, not scaled to fit the console.
from IPython.display import Image, display
display(Image(filename="mypic.png"))
I made a simple tool that will display an image given a filename or image object or url.
It's crude, but it'll do in a hurry.
Installation:
$ pip install simple-imshow
Usage:
from simshow import simshow
simshow('some_local_file.jpg') # display from local file
simshow('http://mathandy.com/escher_sphere.png') # display from url
If you want to open the image in your native image viewer, try os.startfile:
import os
os.startfile('file')
Or you could set the image as the background using a GUI library and then show it when you want to. But this way uses a lot more code and might impact the time your script takes to run. But it does allow you to customize the ui. Here's an example using wxpython:
import wx
########################################################################
class MainPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent=parent)
self.SetBackgroundStyle(wx.BG_STYLE_PAINT) # Was wx.BG_STYLE_CUSTOM)
self.frame = parent
sizer = wx.BoxSizer(wx.VERTICAL)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
for num in range(4):
label = "Button %s" % num
btn = wx.Button(self, label=label)
sizer.Add(btn, 0, wx.ALL, 5)
hSizer.Add((1,1), 1, wx.EXPAND)
hSizer.Add(sizer, 0, wx.TOP, 100)
hSizer.Add((1,1), 0, wx.ALL, 75)
self.SetSizer(hSizer)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
#----------------------------------------------------------------------
def OnEraseBackground(self, evt):
"""
Add a picture to the background
"""
# yanked from ColourDB.py
dc = evt.GetDC()
if not dc:
dc = wx.ClientDC(self)
rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
dc.Clear()
bmp = wx.Bitmap("file")
dc.DrawBitmap(bmp, 0, 0)
########################################################################
class MainFrame(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, size=(600,450))
panel = MainPanel(self)
self.Center()
########################################################################
class Main(wx.App):
""""""
#----------------------------------------------------------------------
def __init__(self, redirect=False, filename=None):
"""Constructor"""
wx.App.__init__(self, redirect, filename)
dlg = MainFrame()
dlg.Show()
#----------------------------------------------------------------------
if __name__ == "__main__":
app = Main()
app.MainLoop()
(source code from how to put a image as a background in wxpython)
You can even show the image in your terminal using timg:
import timg
obj = timg.Renderer()
obj.load_image_from_file("file")
obj.render(timg.SixelMethod)
(PyPI: https://pypi.org/project/timg)
You can use the following code:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
img = mpimg.imread('FILEPATH/FILENAME.jpg')
imgplot = plt.imshow(img)
plt.axis('off')
plt.show()
Displaying images in console using Python
For this you will need a library called ascii_magic
Installation : pip install ascii_magic
Sample Code :
import ascii_magic
img = ascii_magic.from_image_file("Image.png")
result = ascii_magic.to_terminal(img)
Reference : Ascii_Magic
2022:
import os
os.open("filename.png")
It will open the filename.png in a window using default image viewer.
The easiest way to display an image from a console script is to open it in a web browser using webbrowser standard library module.
No additional packages need to be installed
Works across different operating systems
On macOS, webbrowser directly opens Preview app if you pass it an image file
Here is an example, tested on macOS.
import webbrowser
# Generate PNG file
path = Path("/tmp/test-image.png")
with open(path, "wb") as out:
out.write(png_data)
# Test the image on a local screen
# using a web browser.
# Path URL format may vary across different operating systems,
# consult Python manual for details.
webbrowser.open(f"file://{path.as_posix()}")

Categories

Resources