I hope it run and do not stop.
I'm making Conway's Game of Life,
if my code look stupid, please help me, I'm only 11.
I use the details from wiki, if it's wrong , please tell me.
Thankyou!
import turtle,random
START_POSITION=[]
def ReStart():
global START_POSITION
#START_POSITION.clear()
y=500
x=-500
for i in range(1,26):
for a in range(1,26):
START_POSITION.append(eval(f"({x},{y})"))
x+=20
x=(0-300)
y-=20
return True
ReStart()
screen=turtle.Screen()
class Cell:
def __init__(self):
self.cells=[]
self.make_body()
self.a()
self.Alive(screen)
def make_body(self):
global START_POSITION
for i in START_POSITION:
seg=turtle.Turtle(shape="square")
seg.color("White")
seg.penup()
seg.goto(i[0],i[1])
self.cells.append(seg)
The error saids:
Traceback (most recent call last):
File "C:/Users/****/Desktop/寫程式/the life game.py", line 145, in <module>
cell=Cell()
File "C:/Users/****/Desktop/寫程式/the life game.py", line 20, in __init__
self.make_body()
File "C:/Users/****/Desktop/寫程式/the life game.py", line 29, in make_body
seg.goto(i[0],i[1])
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 1777, in goto
self._goto(Vec2D(x, y))
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 3180, in _goto
self._update()
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 2661, in _update
self._update_data()
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 2647, in _update_data
self.screen._incrementudc()
File "C:\Users\****\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 1293, in _incrementudc
raise Terminator
turtle.Terminator
I'm totally stuck on this,please help me.
I've reworked your code fragment into what I believe you are trying to do. Avoid eval as it can cause endless problems. Your use of global in this context isn't valid. See if this works for you:
from turtle import Screen, Turtle
class Body:
def __init__(self, positions):
self.cells = []
self.make_body(positions)
# self.a()
# self.Alive(screen)
def make_body(self, positions):
for position in positions:
cell = Turtle(shape='square')
cell.fillcolor('white')
cell.penup()
cell.goto(position)
self.cells.append(cell)
def restart():
start_positions.clear()
y = 250
for _ in range(25):
x = -250
for _ in range(25):
start_positions.append((x, y))
x += 20
y -= 20
start_positions = []
screen = Screen()
screen.setup(550, 550)
screen.bgcolor('black')
screen.tracer(False)
restart()
my_body = Body(start_positions)
screen.tracer(True)
screen.exitonclick()
Since I've turned off tracer() for speed, call screen.update() whenever you're ready for the user to see the most recent changes.
Related
I am reading a set of coordinates from a file to produce a shape in the Python Turtle. After reading reading in the coordinates, I have written a for loop that goes through the list of coords and draws them. However, upon running with a correct file name, I get this error:
Traceback (most recent call last):
File "C:\Users\06113\Desktop\My Stuff\Python Saves\Vec Draw\Vec Draw.py", line 55, in <module>
t.goto(cs)
File "C:\Users\06113\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 1774, in goto
self._goto(Vec2D(*x))
File "C:\Users\06113\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 3195, in _goto
self._update() #count=True)
File "C:\Users\06113\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 2660, in _update
self._update_data()
File "C:\Users\06113\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 2650, in _update_data
self.screen._drawline(self.currentLineItem, self.currentLine,
File "C:\Users\06113\AppData\Local\Programs\Python\Python38-32\lib\turtle.py", line 543, in _drawline
cl.append(x * self.xscale)
TypeError: can't multiply sequence by non-int of type 'float'
Is there any way at all that I could fix this in MY file? I would rather not go into the turtle module where I could easily mess something up.
The code for this section in my file is:
t = turtle.Turtle(visible=False)
t.speed(0)
for i in range(0, len(coord_list), 2):
if i == 0 and i+1 == 1:
fcs = (coord_list[i], coord_list[i+1])
t.pu()
t.goto(fcs)
t.pd()
pass
else:
cs = (coord_list[i], coord_list[i+1])
t.goto(cs)
cs = None
pass
pass
t.goto(fcs)
print("Vector image drawn.")
Im writing a Sudoku solver UI in Kivy.
I wanted to add a button, which upon being pressed, solves the Grid. The function works, although when I assign it to a button as the on_press function, it somehow runs before the button is pressed. I've tried everything. I get an Assertion Error. When I just use the solve function, it works. Not with the button, though.
Thank you for helping.
This is the __init__ function:
class SudokuGrid(GridLayout):
def __init__(self, **kwargs):
super(SudokuGrid, self).__init__(**kwargs)
self.grid = [[8,7,0, 0,0,0, 0,0,0],
[0,0,0, 9,0,0, 0,0,4],
[0,2,0, 7,0,0, 1,0,5],
[0,0,9, 6,0,0, 0,3,0],
[0,0,0, 0,0,0, 0,0,9],
[0,0,6, 5,4,0, 0,0,0],
[6,9,0, 0,0,0, 7,0,0],
[2,0,0, 0,0,7, 4,0,0],
[0,0,0, 3,0,0, 0,1,0]]
self.add_widget(Button(on_press=self.solve()))
self.cols = 3
self.rows = 4
self.load_grid()
And this my solve function:
def solve(self):
for x in range(9):
for y in range(9):
if self.grid[y][x] == 0:
for n in range(1,10):
if self.possible(y,x,n):
self.grid[y][x] = n
self.solve()
self.grid[y][x] = 0
return
self.load_grid()
print(np.matrix(self.grid))
I know that the function is run, because before the App terminates, I get the output of the solved Grid.
This is the Traceback:
Traceback (most recent call last):
File "C:\Users\victo\Desktop\portfolio\Sudoku\sudoku_app.py", line 217, in <module>
sudoku_game.run()
File "C:\Users\victo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\app.py", line 829, in run
root = self.build()
File "C:\Users\victo\Desktop\portfolio\Sudoku\sudoku_app.py", line 205, in build
self.sudoku_grid = SudokuGrid()
File "C:\Users\victo\Desktop\portfolio\Sudoku\sudoku_app.py", line 73, in __init__
self.add_widget(Button(on_press=self.solve()))
File "C:\Users\victo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\uix\behaviors\button.py", line 121, in __init__
super(ButtonBehavior, self).__init__(**kwargs)
File "C:\Users\victo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\uix\label.py", line 318, in __init__
super(Label, self).__init__(**kwargs)
File "C:\Users\victo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\uix\widget.py", line 369, in __init__
self.bind(**on_args)
File "kivy\_event.pyx", line 419, in kivy._event.EventDispatcher.bind
AssertionError: None is not callable
Okay so i figured it out. Erik said in his comment:
Try on_press=self.solve in stead of on_press=self.solve()
which worked, although I got another Error. I had one too many positional arguments for solve(). I fixed it by defining my method as:
def solve(self, *args)
Everything works now.
After my code prints one dot on the screen it doesn't run again. This is what it tells me in the terminal after I close the turtle screen:
Traceback (most recent call last):
File "/Users/Benjamin/Desktop/Space Digital Scene.py", line 33, in <module>
star(size, x, y, color)
File "/Users/Benjamin/Desktop/Space Digital Scene.py", line 12, in star
drawer.begin_fill()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/turtle.py", line 3322, in begin_fill
self._fillitem = self.screen._createpoly()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/turtle.py", line 497, in _createpoly
return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill="", outline="")
File "<string>", line 1, in create_polygon
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2492, in create_polygon
return self._create('polygon', args, kw)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 2474, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: invalid command name ".!canvas"
My code is
import turtle
import random
def star(size, X, Y, color):
drawer.goto(X, Y)
drawer.color(color)
drawer.begin_fill()
drawer.circle(size)
drawer.end_fill()
hex = ["blue","red","yellow","white"]
screen = turtle.Screen()
turtle.bgcolor("black")
drawer = turtle.Turtle()
drawer.speed("fastest")
x = random.randint(-300,301)
y = random.randint(-300,301)
color = random.choice(hex)
size = random.randint(1,6)
a = 1
b = 100
while True:
if a <= b:
star(size, x, y, color)
drawer.hideturtle()
a + 1
continue
else:
break
screen.mainloop()
You have to assign the new a or use a += 1 and also move some lines inside the while loop to execute them each time:
while True:
if a <= b:
x = random.randint(-300, 301)
y = random.randint(-300, 301)
star(size, x, y, color)
drawer.hideturtle()
a += 1
continue
else:
break
screen.mainloop()
So I'm creating a very basic pong game in python, as one of my first independant projects, just to see what I know and to test myself. Tell me, why won't the Tkinter module work with this code?
HEIGHT=500
WIDTH=800
window=Tk()
window.title('PONG!')
c=Canvas(window,width=WIDTH,height=HEIGHT,bg='black')
c.pack()
def pongstick():
c.create_polygon(20,30, 30,30, 30,100, 20,100, fill='white')
pong1=pongstick()
MID_X = WIDTH/2
MID_Y=HEIGHT/2
c.move(pong1, MID_X, MID_Y)
This returns the following error:
Traceback (most recent call last):
File "/Users/jackstrange/Documents/Untitled.py", line 16, in <module>
c.move(pong1, MID_X, MID_Y)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 2430, in move
self.tk.call((self._w, 'move') + args)
_tkinter.TclError: wrong # args: should be ".4385131376 move tagOrId xAmount yAmount"
I could just be being completely stupid and forgetting something very obvious, but I don't know why this won't work!
You didn't return the ID. Try this:
def pongstick():
return c.create_polygon(20,30, 30,30, 30,100, 20,100, fill='white')
I am writing a program in Python, using matplotlib to (among other things) run an animation showing a numerical solution to the time-dependent Schrodinger Equation.
Everything is working fine, but once an animation has finished running, I would like the window it was in to close itself. My way of doing this (shown below) works, but exceptions are thrown up which I cant seem to catch. It works fine for what I need it to do, but the error looks very messy.
I have an alternative method which works without throwing an error, but requires the user to manually close the window (unacceptable for my purposes). Can someone please point out what I am doing wrong, or suggest a better option?
A simplified version of the relevant parts of my code follows:
from matplotlib import animation as ani
from matplotlib import pyplot as plt
multiplier = 0
def get_data(): # some dummy data to animate
x = range(-10, 11)
global multiplier
y = [multiplier * i for i in x]
multiplier += 0.005
return x, y
class Schrodinger_Solver(object):
def __init__(self, xlim = (-10, 10), ylim = (-10, 10), num_frames = 200):
self.num_frames = num_frames
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111, xlim = xlim, ylim = ylim)
self.p_line, = self.ax.plot([], [])
self.ani = ani.FuncAnimation(self.fig, self.animate_frame,
init_func = self.init_func,
interval = 1, frames = self.num_frames,
repeat = False, blit = True)
plt.show()
def animate_frame(self, framenum):
data = get_data()
self.p_line.set_data(data[0], data[1])
if framenum == self.num_frames - 1:
plt.close()
# closes the window when the last frame is reached,
# but exception is thrown. Comment out to avoid the error,
# but then the window needs manual closing
return self.p_line,
def init_func(self):
self.p_line.set_data([], [])
return self.p_line,
Schrodinger_Solver()
I am running Python 2.7.2 on windows 7, with matplotlib 1.1.0
Thanks in advance
EDIT:
exception and traceback as follows:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 495, in callit
func(*args)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 116, in _on_timer
TimerBase._on_timer(self)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 1092, in _on_timer
ret = func(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 315, in _step
still_going = Animation._step(self, *args)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 177, in _step
self._draw_next_frame(framedata, self._blit)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 197, in _draw_next_frame
self._post_draw(framedata, blit)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 220, in _post_draw
self._blit_draw(self._drawn_artists, self._blit_cache)
File "C:\Python27\lib\site-packages\matplotlib\animation.py", line 240, in _blit_draw
ax.figure.canvas.blit(ax.bbox)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 244, in blit
tkagg.blit(self._tkphoto, self.renderer._renderer, bbox=bbox, colormode=2)
File "C:\Python27\lib\site-packages\matplotlib\backends\tkagg.py", line 19, in blit
tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array))
TclError: this isn't a Tk application
Traceback (most recent call last):
File "C:\Python27\quicktest.py", line 44, in <module>
Schrodinger_Solver()
File "C:\Python27\quicktest.py", line 26, in __init__
plt.show()
File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 139, in show
_show(*args, **kw)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 109, in __call__
self.mainloop()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 69, in mainloop
Tk.mainloop()
File "C:\Python27\lib\lib-tk\Tkinter.py", line 325, in mainloop
_default_root.tk.mainloop(n)
AttributeError: 'NoneType' object has no attribute 'tk'
I can catch the second exception, the AttributeError, by a small change:
try: plt.show()
except AttributeError: pass
but the first part, the TclError, remains no matter what I try
I had the same problem a few minutes before... The reason was a very low interval-value in FuncAnimation. Your code tries to update the graphics evere 1 millisecond - quite fast! (1000 fps might not be needed). I tried interval=200 and the error was gone...
HTH
try with:
if framenum == self.num_frames - 1:
exit()
it works for me...
I am facing the exact same problem, and I managed to solve the issue by creating another Animation class. Essentially, I made two changes:
Write a custom class that overwrites the _stop and _step methods.
Riase an StopIteration error in the update function, instead of using plt.close. The exception will be caught and won't break the script.
Here is the code.
from matplotlib import animation as ani
from matplotlib import pyplot as plt
class FuncAnimationDisposable(ani.FuncAnimation):
def __init__(self, fig, func, **kwargs):
super().__init__(fig, func, **kwargs)
def _step(self, *args):
still_going = ani.Animation._step(self, *args)
if not still_going and self.repeat:
super()._init_draw()
self.frame_seq = self.new_frame_seq()
self.event_source.interval = self._repeat_delay
return True
elif (not still_going) and (not self.repeat):
plt.close() # this code stopped the window
return False
else:
self.event_source.interval = self._interval
return still_going
def _stop(self, *args):
# On stop we disconnect all of our events.
if self._blit:
self._fig.canvas.mpl_disconnect(self._resize_id)
self._fig.canvas.mpl_disconnect(self._close_id)
multiplier = 0
def get_data(): # some dummy data to animate
x = range(-10, 11)
global multiplier
y = [multiplier * i for i in x]
multiplier += 0.005
return x, y
class Schrodinger_Solver(object):
def __init__(self, xlim = (-10, 10), ylim = (-10, 10), num_frames = 200):
self.num_frames = num_frames
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111, xlim = xlim, ylim = ylim)
self.p_line, = self.ax.plot([], [])
self.ani = FuncAnimationDisposable(self.fig, self.animate_frame,
init_func = self.init_func,
interval = 1, frames = self.num_frames,
repeat = False, blit = True)
plt.show()
def animate_frame(self, framenum):
data = get_data()
self.p_line.set_data(data[0], data[1])
if framenum == self.num_frames - 1:
raise StopIteration # instead of plt.close()
return self.p_line,
def init_func(self):
self.p_line.set_data([], [])
return self.p_line,
Schrodinger_Solver()
Schrodinger_Solver()
print(multiplier)
(The code snippet was tested with Python 3.7 and matplotlib 3.4.2.)