PyGTK Change Window Dimensions from Two Entry's - window

It's pretty simple what I'm trying to accomplish here.
Say you put down 320 in the left textbox. That means the width of the window will be 320px. Same applies for height, except for the right textbox.
However when I debug I get this error.
Traceback (most recent call last):
File "./app.py", line 37, in change_size
self.win.set_size_request(width,height)
TypeError: an integer is required
Here's the code.
#!/usr/bin/env python
import gtk
class app:
def __init__(self):
self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.win.set_title("Change Dimensions")
self.win.set_default_size(235, 60)
self.win.connect("destroy", gtk.main_quit)
vbox = gtk.VBox(spacing=4)
hbox = gtk.HBox(spacing=4)
self.entry = gtk.Entry()
self.entry2 = gtk.Entry()
hbox.pack_start(self.entry)
hbox.pack_start(self.entry2)
hbox2 = gtk.HBox(spacing=4)
ok = gtk.Button("OK")
ok.connect("clicked", self.change_size)
hbox2.pack_start(ok)
exit = gtk.Button("Exit")
exit.connect("clicked", gtk.main_quit)
hbox2.pack_start(exit)
vbox.pack_start(hbox)
vbox.pack_start(hbox2)
self.win.add(vbox)
self.win.show_all()
def change_size(self, w):
width = self.entry.get_text()
height = self.entry2.get_text()
self.win.set_size_request(width,height)
app()
gtk.main()

That's because get_text returns a string, but set_size_request requires integers. Simple fix:
width = int(self.entry.get_text())
height = int(self.entry2.get_text())

Related

What is a good way to draw a waveform with pyqt6?

Currently making an application which allows me to make a lightshow with some custom build LED-Controllers and for that i need to draw the waveform of the song on a widget.
Although I managed to do this it is still VERY slow (especially with .wav files longer than a few seconds). The thing is I don't know how to optimise this or if my approach is correct since i cant find anything on the web.
So my question is: what is the right way to go about this? How do audio editors display the waveform and are able to zoom in and out without lag?
So my current attempt at this is by using QGraphicsView and a QGraphicsScene, the latter one supposedly being made to represent a lot of custom graphics items.
The main function to look at here is drawWav() in class WavDisplay
Showcreator.py:
from PyQt6 import uic
from PyQt6.QtCore import (
QSize,
Qt
)
from PyQt6.QtGui import (
QAction,
QPen,
QPixmap,
QPainter,
QColor,
QImage
)
from PyQt6.QtWidgets import (
QMainWindow,
QWidget,
QStatusBar,
QFileDialog,
QGraphicsScene,
QGraphicsView,
QGridLayout
)
import sys
import wave
import pyaudio
import numpy as np
import threading
import soundfile as sf
import threading
class MainWindow(QMainWindow):
# audio chunk rate
CHUNK = 1024
def __init__(self):
super().__init__()
# set window title
self.setWindowTitle("LED Music Show")
# create file button
button_action = QAction("Open .wav file", self)
button_action.setStatusTip("Open a Wave file to the Editor.")
button_action.triggered.connect(self.openWav)
# set status bar
self.setStatusBar(QStatusBar(self))
# create menubar
menu = self.menuBar()
# add file button to status bar
file_menu = menu.addMenu("&File")
file_menu.addAction(button_action)
# create layout
layout = QGridLayout()
layout.setContentsMargins(0,0,0,0)
# create Wave display object
self.waveformspace = WavDisplay()
# add widget to layout
layout.addWidget(self.waveformspace, 0, 1)
self.centralWidget = QWidget()
self.centralWidget.setLayout(layout)
self.setCentralWidget(self.centralWidget)
def openWav(self):
# file selection window
self.filename, check = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","Wave files (*.wav)")
self.file = None
# try to open .wav with two methods
try:
try:
self.file = wave.open(self.filename, "rb")
except:
print("Failed to open with wave")
try:
self.file, samplerate = sf.read(self.filename, dtype='float32')
except:
print("Failed to open with soundfile")
# read file and convert it to array
self.signal = self.file.readframes(-1)
self.signal = np.fromstring(self.signal, dtype = np.int16)
# set file for drawing
self.waveformspace.setWavefile(self.signal)
self.waveformspace.drawWav()
# return file cursor to start
self.file.rewind()
# start thread for the player
# self.player = threading.Thread(target = self.playWav)
# try:
# self.player.daemon = True
# except:
# print("Failed to set player to Daemon")
# self.player.start()
except:
print("Err opening File")
def playWav(self):
lastFile = None
lastpos = None
p = pyaudio.PyAudio()
data = None
sampwidth = None
fps = None
chn = None
farmes = None
currentpos = 0
framespersec = None
while True:
if self.file != lastFile:
# get file info
sampwidth = self.file.getsampwidth()
fps = self.file.getframerate()
chn = self.file.getnchannels()
frames = self.file.getnframes()
lastFile = self.file
# open audio stream
stream = p.open(format = p.get_format_from_width(sampwidth), channels = chn, rate = fps, output = True)
# read first frame
data = self.file.readframes(self.CHUNK)
framespersec = sampwidth * chn * fps
print("file changed")
if self.pos != lastpos:
# read file for offset
self.file.readframes(int(self.pos * framespersec))
lastpos = self.pos
frames = self.file.getnframes()
print("pos changed")
while data and self.running:
# writing to the stream
stream.write(data)
data = self.file.readframes(self.CHUNK)
currentpos = currentpos + self.CHUNK
# cleanup stuff.
self.file.close()
stream.close()
p.terminate()
return
class WavDisplay(QGraphicsView):
file = None
maxAmplitude = 0
fileset = False
def __init__(self):
super().__init__()
def setWavefile(self, externFile):
self.file = externFile
self.fileset = True
# find the max deviation from 0 db to set draw borders
if max(self.file) > abs(min(self.file)):
self.maxAmplitude = max(self.file) * 2
else:
self.maxAmplitude = abs(min(self.file)) * 2
def drawWav(self):
# only draw when there is a set file
if self.fileset:
width = self.frameGeometry().width()
height = self.frameGeometry().height()
vStep = height / self.maxAmplitude
scene = QGraphicsScene(self)
# to draw on the middle of the widget
h = height / 2
# method 1 of drawing: looks at sections of the file and determines the max and min amplitude that would be visible on a single "column" of pixels and draws a vertical line between them
if width < len(self.file):
hStep = len(self.file) / width
drawArray = np.empty((width, 3))
for i in range(width - 1):
buffer = self.file[int(np.ceil(i * hStep)) : int(np.ceil((i + 1) * hStep))]
drawArray[i][0] = (min(buffer) * vStep) + h
drawArray[i][1] = (max(buffer) * vStep) + h
for i in range(width - 1):
self.line = scene.addLine(i, drawArray[i][0], i, drawArray[i][1])
# method 2 of drawing: this only happens when the amount of samples to draw is less than the windows width (e.g. when zoomed in and you can see the individual samples)
else:
hStep = width / len(self.file)
for i in range(len(self.file) - 1):
self.line = scene.addLine(i * hStep, int(self.file[i] * vStep + h), (i + 1) * hStep, int(self.file[i + 1] * vStep + h))
self.setScene(scene)
self.setContentsMargins(0,0,0,0)
self.show()
def resizeEvent(self, event) -> None:
# has to redraw the wave file if the window gets resized
self.drawWav()
# class not used yet
class effectList(QGraphicsView):
bpm = 130
trackBeats = 0
def __init__(self):
super().__init__()
def setBeatsAndBpm(self, trackLenght, Bpm):
self.bpm = Bpm
self.trackBeats = (trackLenght / 60) * self.bpm
main.py:
from PyQt6 import QtCore, QtGui, QtWidgets
from Showcreator import MainWindow
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
app.exec()
In essence: Where do i need to start to make this wave file view like one in for example Audacity? (Aka a fast rendering view which doesnt take ages)
Btw i have looked at seemingly duplicates of this question and as you can see in the code i have an algorythem that is only drawing as many lines as the window is wide and not all the 100000+ lines for each sample so the main problem i have should be the rendering method i guess.
Edit: I have all the data preloaded as im loading a wave file and convert it into a numpy array. And i need to display the file as a whole but be able to zoom in dynamically-

Display text on another process' screen (overlay)

I have a question, its more an OS-based one.
I'm playing a video game and I want to be able to put a textual timer ontop of the game's screen as if it was a part of the game itself.
Now, I can write a program in any language that displays a TextBox with a timer on the screen, but if I run it, the game's process (lets call it game.exe) "loses" its focus and I get my TextBox focused and interactive by the OS.
Is there any option to display that text "ontop" of the game.exe that comes from an entire different process? as if there were "layers" to the screen. Also, this text shouldn't be intractable, clickable or make the game.exe process lose its focus.
Here's a very simple example I drew:
Thanks a lot!
Solved this using a window trick with python and tkinter with some windows api stuff.
The trick is to create a transparent non-clickable window and keep it always on top.
I've basically combined this answer with a bunch of simpler stuff like removing window's border and set to auto fullscreen.
from tkinter import *
import time
import win32gui
import win32api
from win32api import GetSystemMetrics
# WIDTH = 500
# HEIGHT = 500
WIDTH = GetSystemMetrics(0)
HEIGHT = GetSystemMetrics(1)
LINEWIDTH = 1
TRANSCOLOUR = 'gray'
title = 'Virtual whiteboard'
global old
old = ()
global HWND_t
HWND_t = 0
tk = Tk()
# tk.title(title)
tk.lift()
tk.wm_attributes("-topmost", True)
tk.wm_attributes("-transparentcolor", TRANSCOLOUR)
tk.attributes('-fullscreen', True)
state_left = win32api.GetKeyState(0x01) # Left button down = 0 or 1. Button up = -127 or -128
canvas = Canvas(tk, width=WIDTH, height=HEIGHT, highlightthickness=0)
canvas.pack()
canvas.config(cursor='tcross')
canvas.create_rectangle(0, 0, WIDTH, HEIGHT, fill=TRANSCOLOUR, outline=TRANSCOLOUR)
canvas.create_text(WIDTH/2,HEIGHT/2,fill="white",font="Arial 20", text="TEXT GOES HERE")
def putOnTop(event):
event.widget.unbind('<Visibility>')
event.widget.update()
event.widget.lift()
event.widget.bind('<Visibility>', putOnTop)
def drawline(data):
global old
if old !=():
canvas.create_line(old[0], old[1], data[0], data[1], width=LINEWIDTH)
old = (data[0], data[1])
def enumHandler(hwnd, lParam):
global HWND_t
if win32gui.IsWindowVisible(hwnd):
if title in win32gui.GetWindowText(hwnd):
HWND_t = hwnd
win32gui.EnumWindows(enumHandler, None)
tk.bind('<Visibility>', putOnTop)
tk.focus()
running = 1
while running == 1:
try:
tk.update()
time.sleep(0.01)
if HWND_t != 0:
windowborder = win32gui.GetWindowRect(HWND_t)
cur_pos = win32api.GetCursorPos()
state_left_new = win32api.GetKeyState(0x01)
if state_left_new != state_left:
if windowborder[0] < cur_pos[0] and windowborder[2] > cur_pos[0] and windowborder[1] < cur_pos[1] and windowborder[3] > cur_pos[1]:
drawline((cur_pos[0] - windowborder[0] - 5, cur_pos[1] - windowborder[1] - 30))
else:
old = ()
except Exception as e:
running = 0
print("error %r" % (e))

PIL problem, but only when called from within another object( Image doesn't exist)

I am trying to develop a python app for a RaspberryPi on a PC. In order to test one aspect, I have written an object class to emulate an OLED display device (hardware) that the PC cannot use (no I2C). The Wdisp class is simply loaded in place of the hardware driver when using the PC.
I have another class that wraps up the few OLED functions I need ( write text , draw progressbar etc. )
# OLED display object
import os
Win = False
if os.name == 'nt':
Win=True
from WindowsOLED import Wdisp
else:
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
class OLEDDisplay(object):
def __init__(self):
# Raspberry Pi pin configuration:
RST = 24
if Win:
self.disp = Wdisp()
else:
self.disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
# Initialize library.
self.disp.begin()
# Create blank image for drawing.
self.width = 128 #self.disp.width
self.height = 64 #self.disp.height
self._image = Image.new('1', (self.width, self.height))
self.draw = ImageDraw.Draw(self._image)
# Load default font.
self.font = ImageFont.load_default()
self.clear()
def __del__(self):
self.clear()
def __repr__(self):
return 'OLED display object for SSD1306 I2C'
def clear(self):
# Clear display
self.disp.clear()
self.disp.display()
def write(self, text):
self.draw.text((0, 2), text, font=self.font, fill=255)
self._show()
def progressbar(self, percent):
#draw a progress bar on top half of screen
shape_width = self.width * (percent/100)
padding =2
top = padding
bottom = (self.height/2) - padding
x = padding
self.draw.rectangle((x, top, self.width-padding, bottom), outline=255, fill=0)
self.draw.rectangle((x, top, x+shape_width, bottom), outline=255, fill=255)
self._show()
def loadimage(self, imagefile):
#open, convert and display an image
self._image = Image.open(imagefile).resize((self.disp.width,
self.disp.height),
Image.ANTIALIAS).convert('1')
self._show()
def _show(self):
# Display image.
self.disp.image(self._image)
self.disp.display()
If I test this class at the command line
Example:
>>> from OLEDDisplay import*
>>> OD = OLEDDisplay()
>>> OD.progressbar(50)
Its works fine - the OLEDDisplay object draws on a PIL image object, passes the image to the Wdisp object and the Wdisp object converts the image to a BitMapImage and displays in on a Tkinter Label ( self.L ).
#Windows subsitute OLED display class
#displays a label image for testing
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog, messagebox
from tkinter.constants import *
class Wdisp(object):
i=None
width = 128
height =64
_image = None
def __init__(self):
self.master = Tk()
self._image = Image.new('1', (self.width, self.height))
self.i = ImageTk.PhotoImage(self._image)
self.L= Label(self.master, text="label place holder", image=self.i)
self.L.pack(expand=YES, fill=BOTH)
def begin(self):
pass
def image(self, newimage):
self._image = newimage
def display(self):
#display the image
self.i = ImageTk.BitmapImage(self._image)
self.L.config(image=self.i)
However, if I use this in my app or test it in a small app:
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog, messagebox
from tkinter.constants import *
from OLEDDisplay import*
def updateOLED():
text = E.get
print(text)
OD.write(text)
master = Tk()
OD = OLEDDisplay()
E = Entry(master)
B = Button(master, text="update OLED", command = updateOLED)
E.pack()
B.pack()
It fails with a tkinter.TclError: image "pyimage4" doesn't exist:
Traceback (most recent call last):
File "D:\My Documents\PI Projects\Pyprojects\PTPIC\OLEDDisplay test.py", line 19, in <module>
OD = OLEDDisplay()
File "D:\My Documents\PI Projects\Pyprojects\PTPIC\OLEDDisplay.py", line 42, in __init__
self.clear()
File "D:\My Documents\PI Projects\Pyprojects\PTPIC\OLEDDisplay.py", line 52, in clear
self.disp.clear()
File "D:\My Documents\PI Projects\Pyprojects\PTPIC\WindowsOLED.py", line 45, in clear
self.display()
File "D:\My Documents\PI Projects\Pyprojects\PTPIC\WindowsOLED.py", line 36, in display
self.L.config(image=self.i)
File "C:\Python34\lib\tkinter\__init__.py", line 1324, in configure
return self._configure('configure', cnf, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 1315, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "pyimage4" doesn't exist
I have no idea why : perhaps variable scope? perhaps something weird with PIL , so any suggestions welcome.
Cheers Bill

Python 2.7 Tkinter Change Label text on button event

Im very new to Python(2.7) im learning GUI design(Tkinter) and keep running into different syntax/no call method/global name not defined errors when trying to implement a simple label text change from a Entry object on button click. Can someone show me the correct syntax for the action
from Tkinter import *
class Part3:
def __init__(self, parent):
GUIFrame =Frame(parent,width= 300, height=200)
GUIFrame.pack(expand = False, anchor = CENTER)
entry = Entry(text="enter your choice")
entry.place(x=65, y = 10)
self.test = StringVar()
self.test.set('''Hi, I'm a Label :)''')
self.Label1 = Label(parent, textvariable = self.test)
self.Label1.place(x = 85, y = 100)
self.Button2 = Button(parent, text='edit',command=self.LabelChange)
self.Button2.place(x= 80, y = 60)
self.Button3 = Button(parent, text='exit', command= parent.quit)
self.Button3.place(x= 160, y = 60)
def LabelChange(self):
test = self.entry.get()
self.Label1(test)
root = Tk()
MainFrame =Part3(root)
root.title('Input Test')
root.mainloop()
The Idea being on the 'edit' (button2) click, the text of Label1 is changed to the text of entry.
Try:
self.entry = Entry(text="enter your choice")
...
test = self.entry.get()
self.test.set(test)
I know most tutorials give examples using textvariables, but in most cases you don't need them. You can get and set the values in the widget without using textvariable. Textvariables are mostly useful for doing traces on variables. Variable traces are a somewhat advanced technique that you will rarely need.
from Tkinter import *
class Part3:
def __init__(self, parent):
GUIFrame =Frame(parent,width= 300, height=200)
GUIFrame.pack(expand = False, anchor = CENTER)
self.entry = Entry(text="enter your choice") # this needs to be in self
self.entry.place(x=65, y = 10)
self.test = StringVar()
self.test.set('''Hi, I'm a Label :)''')
self.Label1 = Label(parent, textvariable = self.test)
self.Label1.place(x = 85, y = 100)
self.Button2 = Button(parent, text='edit',command=self.LabelChange)
self.Button2.place(x= 80, y = 60)
self.Button3 = Button(parent, text='exit', command= parent.quit)
self.Button3.place(x= 160, y = 60)
def LabelChange(self):
self.test.set(self.entry.get())
root = Tk()
MainFrame =Part3(root)
root.title('Input Test')
root.mainloop()
root.destroy()
Use can use a .after command. For example:
Lbl = Label(text='Hi')
def change():
Lbl.after(3000, lambda: Lbl.config(text="hola")
# Or you can use the one below to remove delay.
Lbl.config(text='hola')
return change
Btn = Button(command=change ())
Lbl.pack()
Btn.pack()

PyGTK FileChooserDialog Keep Getting Errors

Now I made WidgetArea originally for Windows, but being primarily a Linux user. I wanted to make it for Linux as well, but mainly to learn more about the file dialog in PyGTK. So I took a look at this tutorial to have a better understanding of it, while working on this simple, yet small application, as that's easier for me to learn, and understand by experimentation.
So here's my source code.
#!/usr/bin/env python
import sys, os
import pygtk, gtk, gobject
import pygst
pygst.require("0.10")
import gst
class WidgetArea(gtk.Window):
def addwidget(self, w):
self.win = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.win.set_title("Widget")
self.win.set_decorated(False)
self.win.set_has_frame(False)
self.win.set_resizable(False)
self.win.set_keep_above(True)
self.win.set_property('skip-taskbar-hint', True)
self.previewimage = gtk.Image()
self.win.add(self.previewimage)
self.win.show_all()
def pinning(self, checkbox):
if checkbox.get_active():
self.set_keep_above(True)
else:
self.set_keep_above(False)
def change_size(self, w):
width = int(self.entryw.get_text())
height = int(self.entryh.get_text())
self.win.set_size_request(width,height)
def __init__(self):
super(WidgetArea, self).__init__()
self.set_position(gtk.WIN_POS_CENTER)
self.set_title("WidgetArea")
self.set_resizable(False)
self.set_keep_above(True)
self.set_property('skip-taskbar-hint', True)
self.connect("destroy", gtk.main_quit, "WM destroy")
vbox = gtk.VBox(spacing=0)
hbox = gtk.HBox(spacing=0)
hbox2 = gtk.HBox(spacing=0)
hbox3 = gtk.HBox(spacing=0)
hbox4 = gtk.HBox(spacing=0)
self.widgetsize = gtk.Label("Widget Size:")
self.widgetsize.set_size_request(100, 30)
self.entryw = gtk.Entry()
self.entryh = gtk.Entry()
self.entryw.set_text("270")
self.entryw.set_size_request(75, 30)
labelcoma = gtk.Label(",")
labelcoma.set_size_request(10, 30)
self.entryh.set_text("221")
self.entryh.set_size_request(75, 30)
labelspac1 = gtk.Label(" ")
labelspac1.set_size_request(10, 30)
hbox.pack_start(self.widgetsize)
hbox.pack_start(self.entryw)
hbox.pack_start(labelcoma)
hbox.pack_start(self.entryh)
hbox.pack_start(labelspac1, 0, 0, 10)
check = gtk.CheckButton("Pin This Window")
check.set_active(True)
check.connect("clicked", self.pinning)
hbox.pack_start(check, 0, 0, 10)
labelspac2 = gtk.Label(" ")
labelspac2.set_size_request(250, 15)
hbox2.pack_start(labelspac2)
filefilter = gtk.FileFilter()
filefilter.set_name("Images")
filefilter.add_mime_type("image/png")
filefilter.add_mime_type("image/jpeg")
filefilter.add_mime_type("image/gif")
filefilter.add_mime_type("image/tiff")
filefilter.add_mime_type("image/svg+xml")
filefilter.add_pattern("*.jpg")
self.ref_file_button = gtk.FileChooserButton('Add Widget')
self.ref_file_button.set_current_folder("/".join([self.rootdir,"pics"]))
self.ref_file_button.set_filter(filefilter)
self.ref_file_button.connect("file-set", self.on_open_clicked)
hbox3.pack_start(self.ref_file_button, 150, 150, 10)
labelspac5 = gtk.Label(" ")
labelspac5.set_size_request(0, 10)
hbox4.pack_start(labelspac5)
vbox.pack_start(hbox)
vbox.pack_start(hbox2)
vbox.pack_start(hbox3)
vbox.pack_start(hbox4)
self.add(vbox)
self.show_all()
def on_open_clicked(self, widget, data=None):
ref_image_path = widget.get_filename()
self.previewimage.set_from_file(ref_image_path)
self.addwidg.connect("clicked", self.addwidget)
self.addwidg.connect("clicked", self.change_size)
ref_image_path.destroy()
WidgetArea()
gtk.gdk.threads_init()
gtk.main()
I removed the following code (1st), due to the following error (2nd).
self.ref_file_button.set_current_folder("/".join([self.rootdir,"pics"]))
Traceback (most recent call last):
File "./widgetarea.py", line 109, in <module>
WidgetArea()
File "./widgetarea.py", line 86, in __init__
self.ref_file_button.set_current_folder("/".join([self.rootdir,"pics"]))
AttributeError: 'WidgetArea' object has no attribute 'rootdir'
Now this isn't a big deal at this point. My main goal is to get the image displayed in a new window. So after I removed the code above, due to that error I got another one.
Traceback (most recent call last):
File "./widgetarea.py", line 103, in on_open_clicked
self.previewimage.set_from_file(ref_image_path)
AttributeError: 'WidgetArea' object has no attribute 'previewimage'
All I'm having problems with is when you browse to select an image I want the chosen image, when pressed OK to launch as a new window displaying the chosen image in that window, as stated above.
To correct the first error, use gtk.FILE_CHOOSER_ACTION_OPEN instead of gtk.FileChooserAction.OPEN.
The second problem is because there is no variable named image at that point in your code (line 116). Perhaps you are coming from a C++ or Java background, where a name like image can be resolved by looking at the attributes of the enclosing class, i.e. this.image?
In Python you can't do that. You have to assign explicitly to self.image in your addwidget() method. Otherwise the name image remains local to the addwidget() method and is not available outside of it.
This raises a different problem, what happens every time the button gets clicked and addwidget() is called? self.win and self.image are overwritten. That may be what you want, but I'm just calling it to your attention --- it seems a little odd to me.
I have used something like this in one of my projects. And it's working well for me in Linux.
def __init__(self):
# Define all the widgets
image_filter = gtk.FileFilter()
image_filter.set_name("Images")
image_filter.add_mime_type("image/png")
image_filter.add_mime_type("image/jpeg")
image_filter.add_mime_type("image/gif")
image_filter.add_mime_type("image/tiff")
image_filter.add_mime_type("image/svg+xml")
image_filter.add_pattern("*.jpg")
self.ref_file_button = gtk.FileChooserButton('Select Image')
self.ref_file_button.set_size_request(100,30)
self.ref_file_button.set_current_folder("/".join([self.rootdir,"pics"])) # set directory path
self.ref_file_button.set_filter(image_filter)
self.ref_file_button.set_tooltip_text('Select Image')
self.ref_file_button.connect("file-set", self.ref_image_selected)
def ref_image_selected(self,widget,data=None):
ref_image_path = widget.get_filename()
print ref_image_path
After getting the path of the image, you can load it using gtk.Image
EDIT:
Your code is a bit erroneous. You are never calling the function addwidget(), and hence self.previewimage is not defined. and so it gives AttributeError.
def __init__(self):
# your code
self.add(vbox)
self.addwidget(200) # I don't know what 'w' is. so I took a random number.
self.show_all()
def on_open_clicked(self, widget, data=None):
ref_image_path = widget.get_filename()
self.previewimage.set_from_file(ref_image_path)
self.addwidg.connect("clicked", self.addwidget)
self.addwidg.connect("clicked", self.change_size)
ref_image_path.destroy()
What is self.addwidg ?
And I am able to view the image now.

Resources