Error using turtle under Python 2.7 Idle - python-2.7

Why is my code showing an error in turtle()? I am using Python 2.7.13 Idle. The query is regarding to draw a square using turtle:
import turtle
def draw_square():
window=turtle.Screen()
window.bgcolor("red")
brad= turtle.Turtle()
brad.shape("yellow") # move forward
brad.speed(2)# turn pen right 90 degrees
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
window.exitonclick()
draw_square()

You've made a couple of mistakes in your program. First, the window.exitonclick() isn't indented properly such that you're referencing a local variable of draw_square() from outside the function. Your insanely narrow, one space indentation was likely a contributor to this issue.
The next mistake is brad.shape("yellow") as yellow isn't a shape, it's a color. Also, the comments in draw_square() appear to be on the wrong lines. Some might not consider that a mistake, but I do.
Your code reworked to fix the above and lay it out in a more logical fashion for turtle programming:
import turtle
def draw_square(a_turtle):
a_turtle.forward(100) # move forward
a_turtle.right(90) # turn pen right 90 degrees
a_turtle.forward(100)
a_turtle.right(90)
a_turtle.forward(100)
a_turtle.right(90)
a_turtle.forward(100)
a_turtle.right(90)
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed("slow")
draw_square(brad)
turtle.mainloop()

Related

Cannot insert a image in Tkinter Label even after anchoring it

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.

Matplotlib Qt4 GUI programming - replace plt.figure() with OO equivalent

I have an App made using Qt4 Designer which inserts a matplotlib figure into a container widget.
The code to generate the figure comes from another module, obspy:
self.st.plot(fig = self.rawDataPlot)
https://docs.obspy.org/packages/autogen/obspy.core.stream.Stream.plot.html
Normally, this would create and show a matplotlib figure for the st object's data, which is time-series. When the fig parameter is specified this tells self.st.plot to plot to an existing matplotlib figure instance.
The code I have to generate the figure and then position it in my GUI widget is:
def addmpl(self, fig, layout, window): # code to add mpl figure to Qt4 widget
self.canvas = FigureCanvas(fig)
layout.addWidget(self.canvas)
self.canvas.draw()
self.toolbar = NavigationToolbar(self.canvas,
window, coordinates=True)
layout.addWidget(self.toolbar)
self.rawDataPlot = plt.figure() # code to create a mpl figure instance
self.st.plot(fig = self.rawDataPlot) # plot time-series data to existing matplotlib figure instance
self.addmpl(self.rawDataPlot, self.mplvl, self.mplwindow) # add mpl figure to Qt4 widget
What I want to do is instantiate a matplot figure (for use by self.st.plot) but in a way which avoids using plt.figure(), as I have read that this is bad practice when using object-oriented programming.
If I replace plt.figure() with Figure() (from matplotlib.figure.Figure()) I get an error:
AttributeError: 'NoneType' object has no attribute 'draw'
As it stands, the App runs fine if I use plt.figure(), but is there a clean way to avoid using is and is it even necessary for my case?
PS, the code snippets here are taken from a larger source, but I think it gets the point across..
In principle both methods should work.
Whether you set self.rawDataPlot = plt.figure() or self.rawDataPlot = Figure() does not make a huge difference, assuming the imports are correct.
So the error is most probably triggered within the self.st.plot() function. (In general, if you report errors, append the traceback.)
Looking at the source of obspy.core.stream.Stream.plot there is a keyword argument
:param draw: If True, the figure canvas is explicitly re-drawn, which
ensures that existing figures are fresh. It makes no difference
for figures that are not yet visible.
Defaults to True.
That means that apparently the plot function tries to draw the canvas, which in the case of providing a Figure() hasn't yet been set.
A good guess would therfore be to call
self.rawDataPlot = Figure()
self.st.plot(fig = self.rawDataPlot, draw=False)
and see if the problem persists.

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.

Overwriting Existing Python Plots with New Function Call

I would like to overwrite an existing plot I made in python with a new function call. I would like to produce a plot, look at it, then call the same function again with different arguments to produce another plot. I would like the second plot to replace the first plot. That is, I don't want two figure windows open; just the original window overwritten.
I have tried using interactive mode when plotting (ion()), placing plot() and show() calls in different places, and clearing figures. The problems I have are that: 1. I can never overwrite and existing window, I always open more 2. show() blocks the code from continuing and I am unable to perform the 2nd function call 3. I use interactive mode and the window appears for a second before going away
What I'm trying to do seems simple enough, but I'm having great difficulty. Any help is appreciated.
Easiest solution
There are many ways to do this, the easiest of which is to reset the plot's Line2D using its set_ydata(...) method and pyplot.pause. There are versions of matplotlib (<0.9, I believe) which don't have pyplot.pause, so you may need to update yours. Here's a simple minimal working example:
import numpy as np
from matplotlib import pyplot as plt
ph, = plt.plot(np.random.rand(100))
def change_plot():
ph.set_ydata(np.random.rand(100))
plt.pause(1)
while True:
change_plot()
Other approaches
Using pyplot.ion and pyplot.ioff, as detailed here. I tend to use these when I'm doing exploratory data analysis with a Python shell.
Using the matplotlib.animation package, as detailed in this very comprehensible example. This is a much more robust approach than the easy solution above, and permits all kinds of useful/fun options, such as outputting the animation to a video file, etc.
Instead of using the set_ydata method of the Lines object, you can always clear the axes (pyplot.cla()) and call the plotting command again. For example, if you are using pyplot.contour, the returned QuadContourSet has no set_zdata method, but this will work:
import numpy as np
from matplotlib import pyplot as plt
X,Y = np.meshgrid(np.arange(100),np.arange(100))
def change_plot():
Z = np.random.random(X.shape)
plt.cla()
ph = plt.contour(X,Y,Z)
plt.pause(1)
while True:
change_plot()
write your plotting function like
def my_plotter(ax, data, style):
ax.cla()
# ax.whatever for the rest of your plotting
return artists_added
and then call it like
data = some_function()
arts = my_plotter(plt.gca(), data, ...)
or do
fig, ax = plt.subplots()
and then call your plotting function like
arts = my_plotter(ax, data, ...)
I had almost the same issue and I solved it by assigning a name for each plot.
def acc(train_acc, test_acc, savename):
plt.figure(savename) # If you remove this line, the plots will be added to the same plot. But, when you assign a figure, each plot will appear in a separate plot.
ep = np.arange(len(train_acc)) + 1
plt.plot(ep, train_acc, color="blue", linewidth=1, linestyle="-", label="Train")
plt.plot(ep, test_acc, color="red", linewidth=1, linestyle="-", label="Test")
plt.title("NDCG")
plt.xlabel("Iteration")
plt.ylabel("NDCG#K")
plt.legend(loc='lower right')
plt.savefig(savename)

Good sources on general program layout (preferably Python or C++)

So I can do a little C++ console stuff with classes (nothing too fancy I think) and just started with Python (awesome language, it's like C++ without worries) and Tkinter.
The thing is that I don't really have a clue how in general a program with a GUI is structured. I know you have to separate the interface from the internal workings, but that's about it. As an example I am working on a small app that converts Excel tables to LaTeX tables and so far I have this:
from Tkinter import *
class ExcelToLateX:
def __init__(self,master):
self.convert = Button(master,text="Convert",command=self.Conversion)
self.convert.pack(side=BOTTOM,fill=X)
self.input=Input(master,40)
self.output=Output(master,40)
def Conversion(self):
self.output.Write(self.input.Read())
class Input:
def __init__(self,master,x):
self.u=Text(master,width=x)
self.u.pack(side=LEFT)
self.u.insert(1.0,"Paste Excel data here...")
def Read(self):
return self.u.get(1.0,END)
class Output:
def __init__(self,master,x):
self.v=Text(master,width=x)
self.v.pack(side=RIGHT)
self.v.insert(1.0,"LaTeX code")
def Write (self,input):
self.input=input
if self.v.get(1.0,END)=="":
self.v.insert(1.0,self.input)
else:
self.v.delete(1.0,END)
self.v.insert(1.0,self.input)
#Test script
root=Tk()
Window=ExcelToLateX(root)
root.mainloop()
So I have two Text widgets that can read and write stuff and a (for now) empty conversion class that will take Excel tables and spew out LaTeX code. I have no idea if this is the way to go (so any comments/tips are appreciated).
So in short I have two questions:
Are there any widely acknowledged sources that provide information on how a program with a GUI is structured? (preferably Python and Tkinter because that's what I'm doing right know, although it may be a bit more general (cross-language))
Is my current application any good when it comes to structure, and if not, what are some rules of thumb and things I can improve?
I'm just going to throw a couple short comments into the hat. I don't have experience with Tkinter, so my knowledge derives from PyQt4 experience.
Right now you are using composition for your classes, by making the single widget a member attribute. This can obviously work but a useful pattern is to subclass a GUI widget, and then compose the layout by adding more child widgets and parenting to that class. See the examples on this random Tkinter tutorial link I found: http://zetcode.com/tutorials/tkintertutorial/
class Example(Frame):
def __init__(self, parent):
super(Example, self).__init__(parent)
...
And just as a general python convention, you should try and stick with capitalization for your class names, and camelCase or under_score for class instance methods and variables. As you have it, you are using capital for instances (Window =) and methods (Write)
Also, if you aren't going to be subclassing Tkinter widgets, make sure to at least use the new-style classes by subclassing from object: http://realmike.org/blog/2010/07/18/introduction-to-new-style-classes-in-python/
You might also want to nest that last part of your code where you run the event loop inside of the classic python idiom:
if __name__ == "__main__":
root=Tk()
window = ExcelToLateX(root)
root.mainloop()
It prevents your app from immediately being executed if you were to import this module into another application as a library.