Cannot insert a image in Tkinter Label even after anchoring it - python-2.7

Code Here is my code
I've attached a link of well formatted code image and file
import os.
from Tkinter import *.
root=Tk().
m=Label(root,text="Processing...",fg="bue",font="calibri 35 bold").
os.chdir("f:\\").
im=PhotoImage("MM.jpg")
ok=Toplevel(root)
s=Label(root,text="Img",image=im)
s.photo=im
s.image=im
s.grid(row=0,column=0) m.grid(row=1,column=0)
but=None.
def dat():.    
global s,root,but.    
s.destroy().    
m.destroy().
but=Label(root,text="Done").  
but.pack().
  root.overrideredirect(False).
root.mainloop().
I've attached a image of properly indented code in the link
or my file's drive link
Drive link

Please reformat your code so that you can get better help and quickly.
Meanwhile I have a code below showing you how to properly open a .jpg file and have it appear in a tk.Label. I hope this basics can guide you to solve your code problem.
from Tkinter import *
from PIL import Image, ImageTk #added
root=Tk()
filename = "minion.jpg" # Put your filename (can also use full path)here
im = Image.open(filename) #added
im=ImageTk.PhotoImage(im) #revised
s=Label(root,text="Img",image=im)
s.grid(row=0,column=0)
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
root.mainloop()
Update:
I have added the image commands into your script. Do note, your code contained several wrong indents, which pycharm highlighted to me. There were typos, wrong placement of certain commands and missing import statement. I took the liberty to correct them sufficient enough for tkinter to generate a tk window with your label and image, so to be able to answer your question. A screen shot of pycharm with python2.7, a revised code and tk window with label and image is attached below.
Note: For .jpg image you need the PIL or Pillow modules installed to open such file type. Do make sure you have that. If you don't have, follow the instructions in this webpage to install it. That is the limitation of the PIL.ImageTk.PhotoImage method. You can read more from this website.

Related

Better looking Tkinter File Dialogs for Python 2.7

In my application, the user needs to browse for files. However, the askdirectory from tkFileDialog isn't really comfortable for using and browsing files since it's somewhat outdated.
It looks like this:
What I want to achieve should look like the "default" windows browse dialog. Like this:
(Source https://www.pythontutorial.net/tkinter/tkinter-open-file-dialog/)
I am not sure (since I couldn't find proof) but I remember someone telling me that it looks like this because I am using Python 2.7 and not 3+.
Is that true? Does an alternative exist?
It seems it has something to do with your version, as I have done a bit of research and I am using python 3 with the included tkinter and it shows a normal windows explorer popup. So, if you are using one of the up-to-date versions, it should be the OS' default. (I am unable to test that as python 2 will not work properly on my machine although I can confirm since you are using an older one)
I recreated your case with this code:
from tkinter import *
root = Tk()
filedialog.askdirectory()
root.mainloop()
You can try using askopenfilename(). It displays the standard Open File dialog box.
For example:
from tkinter import *
from tkinter import filedialog as fd
root = Tk()
root.title("Button to open files")
root.geometry("500x500")
def openfd(*args):
askk = askopenfilename()
btn = Button(root, text="Click to open file", command=openfd)
btn.place(x=200, y=200)
root.mainloop()
You can read more about it at https://www.pythontutorial.net/tkinter/tkinter-open-file-dialog/.

Use Cartopy Maps Offline

I am trying to plot maps using Cartopy offline. I've found this post:
Location of stored offline data for cartopy
However, after changing cartopy.config['data_dir'] to 'C:/...' where the downloaded files are located, when I try to draw coastlines, it still wants to download the map.
cartopy.config['data_dir'] = '.../CartopyMaps'
ax = plt.axes(projection=ccrs.PlateCarree())
ax.coastlines()
The console says :
Downloading:
http://naciscdn.org/naturalearth/110m/physical/ne_110m_coastline.zip
However, I have ne_110m_coastline dbf, shp, and shx files in .../CartopyMaps/shapefiles/natural_earth/physical/
Why does Cartopy not see my local maps and how can I help it?
Try using the "pre_existing_data_dir" path instead of the "data_dir".
from os.path import expanduser
import cartopy
cartopy.config['pre_existing_data_dir'] = expanduser('~/cartopy-data/')
i had the similar problem and was confused for quite a while. after i downloaded the whole offline dataset and put them in the right dir, after runing the code
...
states = NaturalEarthFeature(category="cultural", scale="50m",
facecolor="none",
name="admin_1_states_provinces_shp")
...
the console still says:
Downloading:
...50m/cultural/ne_50m_admin_1_states_provinces_lines_shp.zip
however, i found there is a slight difference between the file ne_50m_admin_1_states_provinces_lines.shp i downloaded and the file ne_50m_admin_1_states_provinces_lines_shp.zip cartopy tries to acquire ('_shp').
therefore i changed the command into this and it worked:
states = NaturalEarthFeature(category="cultural", scale="50m",
facecolor="none",
name="admin_1_states_provinces")

Phonon not functionning with some mp3s

I'm trying to make a music player with PyQt4 and Phonon. The player works well for most of my music, but some MP3 files won't work.
I tried with a lot of MP3s, approximately 1 out of 10 seems to have the problem. Phonon doesn't send any error, it simply doesn't play the song. Just to be sure, I compared two songs, one working and the other not, and they use the same codec (MPEG-1 Layer 3), both are in 44100Hz and 320 kb/s, tags are in ID3v2.3, neither use any special characters in their tags or filepath, and both work correctly when I play them in WMP.
I initialize the player with :
self.player = Phonon.createPlayer(Phonon.MusicCategory)
then to launch a song, I use :
self.player.setCurrentSource(Phonon.MediaSource(path_to_file))
self.player.play()
Obviously, there must be some difference between the files, maybe in the way they were encoded (the whole album of a non-working song won't work either), but I have no clue why some files are ok and other not... Do you have an idea of what could cause the problem ?
EDIT :
I'm on Windows 10, running PyQt 4.11.4 and Python 2.7.15. Not sure about the Phonon version though... :-/
I think I found something though... I managed to get an error for incorrect MP3s :
"Contacts could not be connected because they do not support the same transport. (0x80040266)."
According to this post, it's caused by the file metadata, and when I did some tests, it looks like it comes from the album cover's file size. When the size is higher than ~108 KB, the MP3 doesn't work, but if I resize the image so that it's below this limit, the MP3 works...
Here's a simplified code to test with a problematic mp3 :
import sys
from functools import partial
from PyQt4.QtGui import *
from PyQt4.phonon import *
class MusicPlayer(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.player = Phonon.createPlayer(Phonon.MusicCategory)
BTN_play = QPushButton("Play")
BTN_play.pressed.connect(self.play)
self.setCentralWidget(BTN_play)
self.show()
def play(self):
path = "path/to/file.mp3"
self.player.setCurrentSource(Phonon.MediaSource(path))
self.player.play()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MusicPlayer()
sys.exit(app.exec_())
Still, I'd prefer not to edit each file metadata to correct it. Could there be a way to make Phonon ignore the cover image when parsing a file so that it doesn't make an error ?

Auto-save function implementation with Python and Tkinter

This might be a general question. I'm modifying a Python code wrote by former colleague. The main purpose of the code is
Read some file from local
Pop out a GUI to do some modification
Save the file to local
The GUI is wrote with Python and Tkinter. I'm not very familiar with Tkinter actually. Right now, I want to implement an auto-save function, which runs alongside Tkinter's mainloop(), and save modified files automatically for every 5 minutes. I think I will need a second thread to do this. But I'm not sure how. Any ideas or examples will be much appreciated!! Thanks
Just like the comment says, use 'after' recursion.
import Tkinter
root = Tkinter.Tk()
def autosave():
# do something you want
root.after(60000 * 5, autosave) # time in milliseconds
autosave()
root.mainloop()
Threaded solution is possible too:
import threading
import time
import Tkinter
root = Tkinter.Tk()
def autosave():
while True:
# do something you want
time.sleep(60 * 5)
saver = threading.Thread(target=autosave)
saver.start()
root.mainloop()
before leaving I use sys.exit() to kill all running threads and gui. Not sure is it proper way to do it or not.

Python: How to import the absolute minimum needed for Matplotlib?

I have a small project that uses matplotlib to display a wafer map of die. I am "compiling" the single-file Python (2.7) into an executable using PyInstaller with the --onefile option, so that non-Python users at the company can execute it in Windows.
The executable takes quite a while to load, up to 15s. As a workaround, I removed all the wafer-map plotting capabilities of the program and built a "Lite" version. This Lite version runs in <1s, as it should. In addition, the Lite version's .exe is 85% smaller (as expected).
So it looks like the Matplotlib stuff is bloating the exe and is making it take a long time to load.
Here's my thought process:
I should be able to get the file size down and decrease the load time if I only import the modules I use rather than all of matplotlib.pyplot. I assume that the import matplotlib.pyplot as pyplot line is importing a whole bunch of extra stuff that I'm not using, such as scatterplots.
Here's my question:
How can I only import the parts of matplotlib that I use?
Here's my (relevant) code, with a lot of the fluff (like line colors) removed. Also, please ignore the lack of PEP8 conformity - this was written before I decided to follow it :-)
from __future__ import print_function
import math
import matplotlib.pyplot as pyplot
import matplotlib.patches
fig = pyplot.figure(1)
ax = fig.add_subplot(111, aspect='equal')
ax.axis([xAxisMin, xAxisMax, yAxisMin, yAxisMax])
die = matplotlib.patches.Rectangle(coords, dieX, dieY)
ax.add_patch(die)
arc = matplotlib.patches.Arc((0, 0),
width=exclDia, height=exclDia, angle=-90,
theta1=ang, theta2=-ang)
flat = matplotlib.lines.Line2D([-flatX, flatX],
[flatY, flatY])
# Extra code that actually adds everything to the figure
fig.show()
So it looks like I'm using only:
matplotlib.pyplot.figure
matplotlib.patches.Rectangle
matplotlib.patches.Arc
matplotlib.lines.Line2D
However, those above are not individual modules in matplotlib (to my knowledge) - they are classes of their parent module (patches, lines, pyplot), so I can't just `import matplotlib.patches.Arc' or anything.
So. What's my next step?