Python Tkinter - Find image file path from PhotoImage - python-2.7

I have a PhotoImage in tkinter called al_p4 but I want to be able to print the file path of the image. Can anyone help. Here is my code:
al_p4 = Image.open("Media/DVD/image.jpg").resize((100, 150), Image.ANTIALIAS)
al_p4 = ImageTk.PhotoImage(al_p4)
Thanks in advance guys ;)

Because I'm still having trouble interpreting exactly what you mean, here are four different answers regarding how to go about printing.
If you simply need to print it and the path will always be constant, use:
print("Media/DVD/image.jpg")
If you need to print something and the path will be different, try:
filepath = "Media/DVD/image.jpg"
al_p4 = Image.open(filepath).resize((100, 150), Image.ANTIALIAS)
al_p4 = ImageTk.PhotoImage(al_p4)
print(filepath)
If you need to print something to a widget, it's going to depend on the kind of widget you want to use. For something small like a file path, a label would probably be good. Look at effbot's documentation for the label widget for more details.
If you want to redirect all print statements to a widget, which can be useful depending on how your GUI is designed, create a class to redirect stdout. Here's an example with a text widget:
import sys
import Tkinter
def nothing():
print("Nothing")
class Application(Tkinter.Frame):
def __init__(self, master = None):
Tkinter.Frame.__init__(self, master)
self.button = Tkinter.Button(text = "Button 1", command = nothing)
self.button.pack()
class StdoutRedirector(Tkinter.Text):
def __init__(self):
Tkinter.Text.__init__(self)
def write(self, message):
printout.insert(Tkinter.END, message)
printout = StdoutRedirector()
printout.pack()
sys.stdout = printout
root = Tkinter.Tk()
app = Application(root)
app.mainloop()

I'm new to coding, so I'll try the best I can =)
Quick answer:
You need to use .filename in the PIL object (Don't works on TK object)
#This is the image:
al_p4 = Image.open("Media/DVD/image.jpg").resize((100, 150), Image.ANTIALIAS)
#This is to show in Tkinter, Notice I added ..._TK
al_p4_TK = ImageTk.PhotoImage(al_p4)
#This is the filepath I think you want:
print(al_p4.filename)

Related

Non-blocking print redirection to Tkinter text widget

I've been able to get print statements redirected to a Tkinter text widget based on the answer to this question. It describes a class to redirect stdout:
class TextRedirector(object):
def __init__(self, widget, tag="stdout"):
self.widget = widget
self.tag = tag
def write(self, str):
self.widget.configure(state="normal")
self.widget.insert("end", str, (self.tag,))
self.widget.configure(state="disabled")
Utilizing the TextRedirector class, I have the following code
import sys
import time
from tkinter import *
root = Tk()
t = Text(root, width = 20, height = 5)
t.grid()
old_stdout = sys.stdout
sys.stdout = TextRedirector(t)
for i in range(5):
print i + 1
time.sleep(1)
sys.stdout = old_stdout
However, this solution seems to be blocking (the text shows up all at once once the for-loop ends).
I have successfully put together a non-blocking solution using Popen and threading, but this isn't an ideal solution due to some unrelated constraints.
Is there a way to have the print statements show up in the text box in real-time?

New window opens on click but does not show anything[Tkinter]

I am using root as the primary window in which when one puts a question, then the answer from either Wikipedia or WolframAlpha is shown in a new window. But, here what happens is that the new window properly opens but does not show anything.
from Tkinter import *
import wolframalpha
import wikipedia
root=Tk()
root1=Tk()
def getinput():
global entry
answer = StringVar()
ques=entry.get()
try:
#wolframalpha
app_id = myappid #value of myappid is there in the original code
client = wolframalpha.Client(app_id)
res = client.query(ques)
answer.set(next(res.results).text)
label=Label(root1, textvariable=answer)
except:
#wikipedia
answer.set(wikipedia.summary(ques).encode('utf-8'))
label=Label(root1, textvariable=answer)
label.pack(side=BOTTOM)
root.geometry("350x80+300+300")
label=Label(root, text="Hi! I am Python Digital Assistant. How can I help you today?")
entry=Entry(root)
submit=Button(root, text="Submit", bg="light green", command=getinput)
exit1=Button(root, text="Exit", bg="red", fg="white", command=root.destroy)
label.pack()
entry.pack(fill=X)
entry.focus_set()
submit.pack(side=LEFT)
exit1.pack(side=LEFT)
root.mainloop()
You don't have to call TK twice you have to use toplevel to achieve that , with that when you provide the question and click on the submit method the answer will pop up in the Toplevel window.
from Tkinter import *
import wolframalpha
import wikipedia
root=Tk()
def getinput():
top = Toplevel()
top.geometry("500x500")
global entry
answer = StringVar()
ques=entry.get()
try:
#wolframalpha
app_id = myappid #value of myappid is there in the original code
client = wolframalpha.Client(app_id)
res = client.query(ques)
answer.set(next(res.results).text)
label=Label(top, textvariable=answer)
except:
#wikipedia
answer.set(wikipedia.summary(ques).encode('utf-8'))
label=Label(top, textvariable=answer)
label.pack(side=TOP)
root.geometry("350x80+300+300")
label=Label(root, text="Hi! I am Python Digital Assistant. How can I help you today?")
entry=Entry(root)
submit=Button(root, text="Submit", bg="light green", command=getinput)
exit1=Button(root, text="Exit", bg="red", fg="white", command=root.destroy)
label.pack()
entry.pack(fill=X)
entry.focus_set()
submit.pack(side=LEFT)
exit1.pack(side=LEFT)
root.mainloop()

PyQt4 - can't get video to run with QMovie or Phonon

I'm having problems getting any video player to work with my PyQt4 setup (having tried both phonon and QMovie). The below QMovie script is from an example where several users commented it as functional. For me, it runs but only opens a window (with Loading... centered) that never actually plays the .gif (I've tried several working .gif files from numerous examples online, so the file is not the problem). I've commented out the results from running the three debugging steps as well.
What can I do next?
import sys
import os
import sip
sip.setapi('QVariant', 2)
from PyQt4 import QtGui, QtCore
class BusyLabel(QtGui.QWidget):
def __init__(self, gif, parent = None, text = None):
QtGui.QWidget.__init__(self, parent)
self.hlayout = QtGui.QHBoxLayout(self)
self.hlayout.setSpacing(0)
self.hlayout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.hlayout)
# Movie
self.movieLabel = QtGui.QLabel(self)
self.movieLabel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
self.movieLabel.setAlignment(QtCore.Qt.AlignCenter)
self.movie = QtGui.QMovie(gif, QtCore.QByteArray(), self)
self.movie.setScaledSize(QtCore.QSize(20,20))
self.movie.setCacheMode(QtGui.QMovie.CacheAll)
self.movie.setSpeed(100)
print self.movie.isValid() #output = False
print self.movie.supportedFormats() #output = []
self.movieLabel.setMovie(self.movie)
self.hlayout.addWidget(self.movieLabel)
# Label
self.label = QtGui.QLabel(text)
self.hlayout.addWidget(self.label)
self.movie.start()
def setText(self, text):
self.label.setText(text)
def start(self):
self.show()
self.movie.start()
def stop(self):
self.hide()
self.movie.stop()
if __name__ == "__main__":
gif = 'test1.gif'
print os.path.exists(gif) #output = True
app = QtGui.QApplication(sys.argv)
player = BusyLabel(gif)
player.setText('Loading...')
player.start()
player.show()
sys.exit(app.exec_())
output:
True
False
[]
(For those curious about my other attempts, running a popular Phonon script gave the error: phonon backend plugin could not be loaded... I'll take anything at this point)
I'm providing here complete, working code that I've written to answer this (my) problem. All you need is PyQt4 and Matplotlib, I hope this might help someone else facing similar troubles down the road:
https://github.com/evanseitz/PyQt4_VideoPlayer

PyQt 4: Get Position of Toolbar

Hy guys,
in my executable program there is a toolbar. Well, the user decides to move the toolbar. Now the toolbar is floating. I know I have to conntect the floating-signals that is emittted when the toolbar ist arranged by the user. How can I save the new position of the toolbar? I know the method of adding the toolbar to the main window with a position:self.addToolBar( Qt.LeftToolBarArea , toolbar_name). In the handle_floating()-method you see what I want: There I want to get the position currently, but how? You also see I have just added one member variable, named self.toolbar_pos, to hold the position of the toolbar. My idea is, when application is terminated I want to serialize this value to a file, and later, when application is ran again its will read that file and set the toolbar accordingly. But this is no problem. Currently I don't have no idea to get the position of the toolbar.
I need your help :)
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.toolbar_pos = None
self.initUI()
def initUI(self):
exitAction = QtGui.QAction(QtGui.QIcon('exit24.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(QtGui.qApp.quit)
self.toolbar = QtGui.QToolBar(self)
self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.addToolBar(self.toolbar )
self.toolbar.addAction(exitAction)
self.toolbar.setAllowedAreas(QtCore.Qt.TopToolBarArea
| QtCore.Qt.BottomToolBarArea
| QtCore.Qt.LeftToolBarArea
| QtCore.Qt.RightToolBarArea)
self.addToolBar( QtCore.Qt.LeftToolBarArea , self.toolbar )
self.toolbar.topLevelChanged.connect(self.handle_floating)
def handle_floating(self, event):
# The topLevel parameter is true
# if the toolbar is now floating
if not event:
# If the toolbar no longer floats,
# then calculate the position where the
# toolbar is located currently.
self.toolbar_pos = None
print "Get position: ?"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.setGeometry(300, 300, 300, 200)
ex.setWindowTitle('Toolbar example')
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The QMainWindow class already has APIs for this: i.e. saveState and restoreState. These can be used to save and restore the state of all the toolbars and dock-widgets in your application.
To use them, you first need to make sure that all your toolbars and dock-widgets are given a unique object-name when they are created:
class Example(QtGui.QMainWindow):
...
def initUI(self):
...
self.toolbar = QtGui.QToolBar(self)
self.toolbar.setObjectName('foobar')
Then you can override closeEvent to save the state:
class Example(QtGui.QMainWindow):
...
def closeEvent(self, event):
with open('/tmp/test.conf', 'wb') as stream:
stream.write(self.saveState().data())
(NB: I've just used a temporary file here for testing, but it would obviously be much better to use something like QSettings in your real application).
Finally, you can restore the state that was saved previously:
class Example(QtGui.QMainWindow):
def __init__(self, parent=None):
...
self.initUI()
try:
with open('/tmp/test.conf', 'rb') as stream:
self.restoreState(QtCore.QByteArray(stream.read()))
except IOError:
pass

How to add url to bookmark?

I am using PyQt4 for creating a custom browser using QtWebKit, but I am stuck on saving bookmarks from the browser. Does anyone know how to achieve that?
You're a little vague on how you want this done, so I'll say we wanted to use a button imported from a UI file called bookmarks_Btn. You'll need to use the pickle module.
Here's the example code...
from PyQt4 import QtCore, QtGui, QtWebKit, uic
import pickle
class window(QtGui.QWidget):
def __init__(self, parent=None):
super(httpWidget, self).__init__(parent)
self.ui = uic.loadUi('mybrowser.ui')
self.ui.setupUi(self)
def bookmarksLoad(self):
print 'Loading bookmarks'
try:
bookOpen = open('bookmarks.txt', 'rb')
bookmarks = pickle.load(bookOpen)
bookOpen.close()
print bookmarks # Not necessary, but for example purposes
# Here you decide how "bookmarks" variable is displayed.
except:
bookOpen = open('bookmarks.txt', 'wb')
bookmarks = 'http://www.stackoverflow.com'
bookWrite = pickle.dump(bookmarks, bookOpen)
bookOpen.close()
print bookmarks # Not necessary, but for example purposes
# Here you decide how "bookmarks" variable is displayed.
QtCore.QObject.connect(self.ui.bookmarks_Btn, QtCore.SIGNAL('clicked()'), self.bookmarksLoad)
self.ui.show()
def bookmarks():
url = input 'Enter a URL: '
bookOpen = open('bookmarks.txt', 'wb')
bookOpen.write(url)
bookOpen.close()
print 'Website bookmarked!'
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
run = window()
bookmarks()
sys.exit(app.exec_())
# You add on here, for example, deleting bookmarks.
However, if you wanted it to be retrieved from an address bar (named address, make the following changes...
# In the bookmarks function...
global url # Add at beginning
# Remove the input line.
# Add at end of __init__ in window class:
url = self.ui.address.text()
global url
That's pretty much the basics. Please note I normally program in Python 3 and PyQt5 so if there are any errors let me know :)