I'm currently following this link with a tutorial:
Here is the one I am following. The dude gives you the code. Have included it at the bottom anyway.
Would definitely recommend. But now facing issues:
Using Spyder 2.3.8
Python 3.5
Everything up to date
Have set the backend for Spyder to read matplotlib as 'TkAgg' (also took ages!).
Have hashtagged out the three lines which are causing the issue. Works fine when these lines aren't active. Activating them and running causes my terminal to crash and get the message:
It seems the kernel died unexpectedly. Use 'Restart kernel' to continue using this console.
I have really been looking everywhere for a solution. The objective is to get a chart into a Tkinter GUI without it crashing. Please help!?
Here is the code, nearly identical to the one provided in the link:
import matplotlib
#matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import tkinter as tk
import pandas as pd
from tkinter import ttk
LARGE_FONT=("Consolas",12)
class SeaofBTCapp(tk.Tk):
def __init__(self,*args,**kwargs):
#
#tk.Tk.wm_title(self,"")
print("")
tk.Tk.__init__(self,*args,**kwargs)
tk.Tk.wm_title(self,"Hold my Hand")
tk.Tk.iconbitmap(self,default="1.ico")
container=tk.Frame(self)
container.pack(side="top", fill="both",expand=True)
container.grid_rowconfigure(0,weight=1)
container.grid_columnconfigure(0,weight=1)
self.frames={}
for F in (StartPage,PageThree):
frame=F(container, self)
self.frames[F]=frame
frame.grid(row=0,column=0,sticky="nsew") #north south east west
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
def qf(stringtoprint):
print(stringtoprint)
class StartPage(tk.Frame):
def __init__(self,parent,controller):
ttk.Frame.__init__(self,parent)
label=ttk.Label(self,text="Testing",font=LARGE_FONT)
label.pack(pady=10,padx=10)
button3=ttk.Button(self, text="Graph page",
command=lambda:controller.show_frame(PageThree))
#lambda:controller.show_frame(PageOne))
button3.pack()
class PageThree(tk.Frame):
def __init__(self, parent, controller):
# app=tk.Tk()
tk.Frame.__init__(self,parent)
label=tk.Label(self,text="Graph Page",font=LARGE_FONT)
label.pack(pady=10,padx=10)
label1=ttk.Button(self, text="Start Page",
command=lambda:controller.show_frame(StartPage))
label1.pack()
label1=ttk.Button(self, text="Back to Home",
command=lambda:controller.show_frame(StartPage))
label1.pack()
# f=Figure(figsize=(5,5))
# a=f.add_subplot(111)
# a.plot([1,2,3,4,5,6,7,8],[5,6,7,8,1,2,2,1])
# canvas=FigureCanvasTkAgg(f,self)
# canvas.show()
# canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH,expand=True)
app=SeaofBTCapp()
app.mainloop()
It's the above three-six lines that cause Spyder to crash.
Uninstalling the conda version and installing it via pip fixes it.
There is an issue about that: https://github.com/ContinuumIO/anaconda-issues/issues/979
I was struggling with the same problem for a couple of days (Python 3.5.2/64-bit, matplotlib 1.5.1, Win 10 Professional). Reinstallation of matplotlib, tkinter and Python didn't help. Tkinter + matplotlib in Anaconda didn't work as well. Since I am not savvy enough to build matplotlib from the source, I just installed Ubuntu + Anaconda and it helped to solve the issue.
There is something wrong with the code you posted (i.e. indention etc.), I didn't try to fix it. But the following code is working on Ubuntu:
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
fig = Figure()
plt = fig.add_subplot(111)
plt.plot([1, 2], [1, 2])
root = tk.Tk()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
root.update()
root.mainloop()
I hope, it helped.
Related
I try to import and run selfmade modules under Spyder.
The main.py programm
import rot
f=rotor(b_x,b_y,b_z,x,y,z)
The rot.py programm
def rotor(bx,by,bz,x,y,z):
import numpy as np
...
The issue is:
File "C:\Users\Professional.spyder-py3\my_pro\jgut\main.py", line 93, in
f=rotor(b_x,b_y,b_z,x,y,z)
NameError: name 'rotor' is not defined
Problem doesn't disappear even after starting brut force start of any imported modules.
Is there a way to start all imported modules simultaniously? Or maybesomeone faced this problem?
P.S. Problem appeared today after Anaconda reinstall, becouse of incopatebilities with IK-Multimedia apps (I just removed them). I was starting all the mudules by brut force from the begining.
1) Please, do not import modules in functions!
2) rotor is not defined because it is in the rot namespace. You can call it by rot.rotor(args). If you wanted to do call it the way you do, you have to import it like this: from rot import rotor or from rot import * (which imports everything from the rot module and is a bad practise - you should only import what you need).
The error has nothing to do with anything written in the last 2 paragraphs.
I made an executable gui (with tkinter) file using cx_freeze. The executable has several buttons. When the user click the button, the calculation should work and then it will write out an xlsx file.
Everything went good when I make the executable, there was no error. But when I click the button, it seems like the calculation works (since it was loading), but then it does not write out the xlsx file.
I don't know what went wrong. Anyone can help me?
Here's the setup.py file:
import sys
from cx_Freeze import setup, Executable
import os
import tkinter
base = None
if sys.platform == 'win32':
base = "Win32GUI"
executables = [Executable("gui.py", base=base)]
packages = ["tkinter", 'xlsxwriter', 'matplotlib']
options = {
'build_exe': {
'includes': ["os", "tkinter", 'numpy.core._methods', 'numpy.lib.format', 'xlrd', 'scipy', 'pandas'],
'include_files': [r"C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\DLLs\tcl86t.dll",
r"C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\DLLs\tk86t.dll"]
},
}
os.environ['TCL_LIBRARY'] = r'C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
setup(
name="Tool",
version="1.0",
description="Tool prototype for calculating",
options=options,
executables=executables
)
I've solved the problem.
What i did was to change the base in setup.py to : base = None
and I installed the xlsxwriter by following this thread: ImportError: No module named 'xlsxwriter': Error in bamboo
After this, I encountered another problem:
No module named: scipy.sparse.csgraph._validation
but I simply add this to the 'includes': ['scipy.sparse.csgraph._validation', ...]
now everything works perfectly.
I hope this helps anyone who has the same problem.
I'm trying to run the following code:
# To use interactive plots (mouse clicks, zooming, panning) we use the nbagg back end. We want our graphs
# to be embedded in the notebook, inline mode, this combination is defined by the magic "%matplotlib notebook".
%matplotlib notebook
import SimpleITK as sitk
%run update_path_to_download_script
from downloaddata import fetch_data as fdata
import gui
# Using an external viewer (ITK-SNAP or 3D Slicer) we identified a visually appealing window-level setting
T1_WINDOW_LEVEL = (1050,500)
When I run it in spider 3.2.6 I get:
ModuleNotFoundError: No module named 'gui'
Any help would be appreciated.
Code source: http://insightsoftwareconsortium.github.io/SimpleITK-Notebooks/Python_html/30_Segmentation_Region_Growing.html
This isn't a spyder issue.
The gui module is part of the notebooks repository. Either clone the repository or just download this file. Same goes for the downloaddata module.
I'm trying to make a custom legend using matplotlib. The example in the matplotlib documentation doesn't work on my set up. Neither does this follow.
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
fig, ax = plt.subplots()
patch1 = mpatches.Patch(color='#a6cee3', label='Blue')
patch2 = mpatches.Patch(color='#1f78b4', label='Bluerish')
patch3 = mpatches.Patch(color='#33a02c', label='Greener')
patch4 = mpatches.Patch(color='#fdbf6f', label='Kind of orange')
patch5 = mpatches.Patch(color='#ff7f00', label='Orange')
all_handles = (patch1, patch2, patch3, patch4, patch5)
leg = ax.legend(all_handles)
ax.add_artist(leg)
plt.show()
How can I make it produce the desired legend?
I'm using Mac OSX 10.10.3, Python 2.7.6, Matplotlib 1.3.1.
Edit: #xnx's solution below works for Python 3, and works for Python 2.7.11 if using Matplotlib 2.1.1 (thanks #DavidG).
You should set the handles argument to ax.legend explicitly:
leg = ax.legend(handles=all_handles)
I think the issue with your code is that the first (positional) argument to legend is otherwise taken to be a sequence of objects you wish to label and you don't have any.
I had a similar issue.
This solved it for me:
leg = **plt**.legend(all_handles)
I have been following tutorials of how to create a graphical user interface (GUI), in order to get used to it because I will use it in the future. The majority of tutorials use these commands at the first lines:
from tkinter import *
root = tk()
root.title("Simple GUI")
root.geometry("200x100")
root.mainloop()
If I run this simple code I get the following error:
File
"C:/Users/Gerard/Dropbox/Master_Thesis_Gerard_Pujol/Python_Tryouts/creting_simpleGUI.py", line 11, in
root=tk()
NameError: name 'tk' is not defined
After that I changed my code, so I used something like that:
import tkinter as tk
root = tk()
root.title("Simple GUI")
root.geometry("200x100")
root.mainloop()
Now, the error is the following:
"C:/Users/Gerard/Dropbox/Master_Thesis_Gerard_Pujol/Python_Tryouts/creting_simpleGUI.py", line 11, in
root=tk()
TypeError: 'module' object is not callable
Do you know what's going wrong? Could you help me please?
I'm using Spyder for Python 3.3, but I suppose it isn't a problem.
The tutorials you've seen is probably for Python 2. In Python 3 they've changed the naming conventions. So instead of root = tk() in P2, it's root = Tk() in P3 (Tk() is a class, hence the capital T).
In your second example your should write root = tk.Tk() after the import statement
I've just had a similar problem which I found out was because my Python console window in Spyder was connected to a different .py file that I was working on earlier so I closed it and opened a new python console in Spyder and the problem was gone.