trying to draw using Turtle - python-3.x

i have written a simple code that should draw a square, see below:
from turtle import Screen,Turtle
def draw(directions,length,angle,x=0,y=0):
s = Screen
t = Turtle
t.up()
t.setpos(x,y)
t.down()
# iterate over directions
for move in directions:
if move =='F':
t.forward(length)
elif move == 'L':
t.lt(angle)
elif move =='R':
t.rt(angle)
else:
pass
s.exitonclick()
but I get an error message that I dont understand. See below
>>> draw('FLFLFLFL',50,90)
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
draw('FLFLFLFL',50,90)
File "C:/Documents and Settings/RonnieE/Mina dokument/GradSchool/CSC401/Homework
7/test1.py", line 11, in draw
t.up()
TypeError: penup() missing 1 required positional argument: 'self'
What did I do wrong?

This:
s = Screen
t = Turtle
should be:
s = Screen()
t = Turtle()
Otherwise, s and t are just new names for the Screen and Turtle classes. Call the class to generate an instance.
Also, s.exitonclick() should be inside the draw definition (aligned with the for).

Related

Weird illegal tkinter state when calling `widget.destroy` from a `widget.after` script

I was creating a simple program (a label that refreshes itself every 0.1 sec) but I ran into a problem. This is my code:
import tkinter as tk
def loop():
global label
# If the label exists, destroy it
if label is not None:
label.destroy()
# Create a label
label = tk.Label(root)
label.pack() # You don't even need this line for the error
# After some time call `loop` again
label.after(100, loop)
label = None
root = tk.Tk()
# Start the loop
loop()
root.mainloop()
The error traceback shows:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Program Files\Python37\lib\tkinter\__init__.py", line 752, in callit
self.deletecommand(name)
File "C:\Program Files\Python37\lib\tkinter\__init__.py", line 601, in deletecommand
self._tclCommands.remove(name)
AttributeError: 'NoneType' object has no attribute 'remove'
When I changed label.after(...), into root.after(...) it worked. My guess is that tkinter goes in an illegal state after I call label.destroy() from the label.after(...) script. I don't know if the problem comes from tkinter or _tkinter.
Can anyone prove that that's causing problem or suggest another explanation?
PS: Python 3.7.9
I don't know how or what or why is the problem but I think I fixed it (it doesn't throw an error at least) maybe it happens because the widget gets destroyed while it has the .after still affecting it or sth like that:
import tkinter as tk
def loop():
global label
# If the label exists, destroy it
if label:
label.after(0, label.destroy)
# Create a label
label = tk.Label(root)
label.pack() # You don't even need this line for the error
# After some time call `loop` again
label.after(100, loop)
label = None
root = tk.Tk()
# Start the loop
loop()
root.mainloop()
Another thing is that it manages to do exactly 2 full loops before throwing an error

How can I create a Text wiget in Tkinter, Python 3.8

I wanted to make a text wiget in window, but saw this traceback:
Traceback (most recent call last):
File "D:/хрень на питоне/experement3.py", line 18, in <module>
vl=Text(root, width = 20, heigth = 100 , wrap = WORD)
File "C:\Users\Людмилп\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 3554, in __init__
Widget.__init__(self, master, 'text', cnf, kw)
File "C:\Users\Людмилп\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 2567, in __init__
self.tk.call(
_tkinter.TclError: unknown option "-heigth"
My code looked like this:
from tkinter import *
root=Tk()
root.geometry('400x300')
app=Frame(root)
app.grid(row=2,column=0,sticky=S)
bt=Button(app,text='''
First button
''')
bt.grid()
app1=Frame(root)
app1.grid(row=2,column=1,sticky=S)
bt1=Button(app1,text='''
Second button
''')
bt1.grid()
vlf=Frame(root)
vlf.grid(row=0,column=3)
vl=Text(root, width = 20, heigth = 100 , wrap = WORD)
vl.grid()
root.mainloop()
What could went wrong?
Please read your error messages carefully because they almost ever contain useful information. In this case it tells you that in line 18 where you initialise the Text widget you give it an option "heigth" which it can't take. This is due to the fact that you just misspelled "height" by switching "t" and "h" which can happen and is just human.
PS: Your english isn't bad, don't worry. ^^

Resize image in Tkinter

So, I need to resize an image in tkinter. Before you do anything - this is not a duplicate. I have gone through every other question on this site and none have helped me. The thing with me is - I don't wan't to save the image. I need to load the image, resize it, then display it with PhotoImage in a label. I tried to use ImageTk, but for some reason it won't work.
Here's my code with ImageTk:
from tkinter import *
import PIL
from PIL import Image, ImageTk
root = Tk()
left_nose_path_white = Image.open(r'C:\Users\User\Documents\Python stuff\Other apps\Veteris\Dog photos\Advanced\Sides\GIF\Nose\Nose (left) - White.gif')
def resize_image():
global left_nose_path_white
total_screen_width = root.winfo_screenwidth()
total_screen_height = root.winfo_screenheight()
frame_width, frame_height = left_nose_path_white.size
dog_new_width = int(frame_width / 3)
dog_new_height = int(frame_height / 3)
left_nose_path_white = left_nose_path_white.resize((dog_new_width, dog_new_height), Image.LANCZOS)
resize_image()
left_nose_img_white = ImageTk.PhotoImage(file = left_nose_path_white)
label = Label(image = left_nose_img_white)
label.pack()
root.mainloop()
This returns the error:
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 124, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
My code should find the width and height of the original image, divide it by 3, and then show it. The reason I don't want to have to save the image is because the user will open the application several times.
I'm new to using PILL/Pillow, so the answer may be obvious.
I have Pillow installed using pip.
I only have one version of Python on my computer (Python 3.7)
Full Error:
Traceback (most recent call last):
File "C:\Users\User\Documents\Python stuff\Other apps\Veteris\Scripts\Veteris_program.py", line 230, in <module>
left_nose_img_white = ImageTk.PhotoImage(file = left_nose_path_white)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 95, in __init__
image = _get_image_from_kw(kw)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 64, in _get_image_from_kw
return Image.open(source)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2779, in open
prefix = fp.read(16)
AttributeError: 'Image' object has no attribute 'read'
Exception ignored in: <function PhotoImage.__del__ at 0x000002B0A8A49950>
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\ImageTk.py", line 124, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Thanks for the help!

What does "TypeError: 'NoneType' object is not subscriptable" mean?

I am writing a snake game using Pygame in Python3. However, I keep getting this TypeError, not only do I have no idea what it means I have no idea how to fix it
I haven't really attempted anything as I have no idea what it is or how to fix it. This is the code:
def draw(self, surface, eyes=False):
dis = self.w // self.rows
i = self.pos[0]
j = self.pos[1]
The error message I keep getting is:
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "snake.py", line 179, in <module>
main()
File "snake.py", line 175, in main
redrawWindow(win)
File "snake.py", line 127, in redrawWindow
snack.draw(surface)
File "snake.py", line 25, in draw
i = self.pos[0]
TypeError: 'NoneType' object is not subscriptable
This occurs when you try to index through a Nonetype object, e.g.,
>>> x = None
>>> x[0]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x[0]
TypeError: 'NoneType' object is not subscriptable
To properly solve your problem, please post the full code or where you set the initial value of self.pos. It seems that you're setting this variable to None.
This appears to be an excerpt from the python tutorial by Tech With Tim: https://techwithtim.net/tutorials/game-development-with-python/snake-pygame/tutorial-1/
It is actually caused by a misplaced return inside of the randomSnack while loop.
Full code here: https://pastebin.com/embed_js/jB6k06hG
If the return is inside the while loop (at line 162 in the pastebin) you get this error. I was following the same tutorial and got this error too.
# When you call (line 145)
snack.draw(surface)
# you are referencing the snack that was created with (line 193)
snack = cube(randomSnack(rows, s), color=(0,255,0))
# The randomSnack function returns an x and y (line 162)
return (x,y)
# that gets passed into the cube object's "start" parameter (line 12)
def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):

How to fill to lower-right corner in python-curses

I'm using curses in Python3.3 and need to fill the entire usable space with characters. The error I'm getting occurs when my double for loop reaches the last corner.
Traceback (most recent call last):
File "main.py", line 14, in <module>
curses.wrapper(main)
File "/usr/local/lib/python3.3/curses/__init__.py", line 94, in wrapper
return func(stdscr, *args, **kwds)
File "main.py", line 9, in main
stdscr.addch(y, x, ord('.'))
_curses.error: addch() returned ERR
I've noticed that each time a character is added, the cursor moves to the right. I haven't tested this as thoroughly as I might have, but I suspect that the cursor leaves the end of the window on that last call to stdscr.addch, which likely causes the error.
An additional note is that by using a maximum width or height one unit under what the window returns, I'm able to loop without an error.
Source that fails:
import curses
def main(stdscr):
height, width = stdscr.getmaxyx()
for y in range(height):
for x in range(width):
stdscr.addch(y, x, ord('.'))
stdscr.refresh()
stdscr.getch()
if __name__ == '__main__':
curses.wrapper(main)
For my project, it's important that I use a complete rectangle. Up to this point I've shortened my max width from 80 to 79, but if anyone knows a way to write to that last corner, I'd like to hear it.
Calling insch in corner instead of addch worked for me.

Resources