Python 3.7.2 Turtle source folder-specific error message - python

I have installed Python 3.7.2 in Windows 7. When I write turtle code and save it in the Python folder, it runs without errors. If I save it in another folder, it returns this error:
NameError: name dot is not defined.
Here is my code:
from tkinter import *
from tkinter import ttk
from turtle import *
def triangle():
fd(200);left(135);fd(150);goto(0,0)
def rectangle():
lt(180);fd(250);lt(90);fd(125);lt(90);fd(250);lt(90);fd(125)
def square():
fd(250);rt(90);fd(250);rt(90);fd(250);rt(90);fd(250)
def grdk():
circle(75)
window=Tk()
window.title('GeoFigs')
window.geometry('250x200')
label=Label(window,text='Choose one figure',font='Aharoni -22 bold')
label.pack()
sekunga=ttk.Button(window,text='TRIANGLE',command=triangle)
sekunga.pack()
chor=ttk.Button(window,text='RECTANGLE',command=rectangle)
chor.pack()
kv=ttk.Button(window,text='SQUARE',command=square)
kv.pack()
grd=ttk.Button(window,text='CIRCLE',command=grdk)
grd.pack()
mainloop()

I'm not sure if it has anything to do with your "NameError: name dot is not defined" issue but I wouldn't begin to debug a turtle program set up like this one. Turtle is designed to work in either standalone (turtle alone) or embedded (turtle and tkinter) mode but you have it embedded in standalone mode which risks creating two Tk roots and other issues. Below is a rework of your turtle code in embedded mode:
from tkinter import *
from turtle import ScrolledCanvas, TurtleScreen, RawTurtle
def triangle():
turtle.forward(200)
turtle.left(135)
turtle.forward(150)
turtle.home()
def rectangle():
turtle.left(90)
for _ in range(2):
turtle.left(90)
turtle.forward(250)
turtle.left(90)
turtle.forward(125)
def square():
for _ in range(4):
turtle.forward(200)
turtle.right(90)
def circle():
turtle.circle(75)
window = Tk()
window.title('Graphics')
window.geometry('640x480+300+0')
figures = Toplevel(window)
figures.title('Figures')
figures.geometry('250x150')
Label(figures, text='Choose one figure').pack()
Button(figures, text='TRIANGLE', command=triangle).pack()
Button(figures, text='RECTANGLE', command=rectangle).pack()
Button(figures, text='SQUARE', command=square).pack()
Button(figures, text='CIRCLE', command=circle).pack()
canvas = ScrolledCanvas(window)
canvas.pack(fill="both", expand=True)
screen = TurtleScreen(canvas)
screen.screensize(640, 480)
turtle = RawTurtle(screen)
screen.mainloop()
Try this out and if the "NameError: name dot is not defined" persists, provide us a full error backtrace as an edit to your original question.

Related

Turtle screen closes almost immediately after opening

I writed some code from a python book and the book shows that if you run the code there will be no problem
but when I ran the code there was a problem
This is my code:
import turtle
import time
turtle.pensize(5)
turtle.bgcolor("black")
turtle.pencolor("white")
turtle.turtlesize(2,2,2)
def ileri():
turtle.fd(5)
def geri():
turtle.backward(5)
def sag():
turtle.right(90)
turtle.fd(5)
turtle.left(90)
def sol():
turtle.left(90)
turtle.fd(5)
turtle.right(90)
def sagdon():
turtle.right(10)
def soldon():
turtle.left(10)
def siyah():
turtle.pencolor("black")
def yesil():
turtle.pencolor("green")
def acikyesil():
turtle.pencolor("lightgreen")
def mavi():
turtle.pencolor("blue")
def acikmavi():
turtle.pencolor("lightblue")
def sari():
turtle.pencolor("yellow")
def kirmizigul():
turtle.pencolor("red")
turtle.onkeypress(ileri, "w" or "Up")
turtle.onkeypress(geri, "s" or "Down")
turtle.onkeypress(sag, "d")
turtle.onkeypress(sol, "a")
turtle.onkeypress(sagdon, "Right")
turtle.onkeypress(soldon, "Left")
turtle.onkeypress(siyah, "0")
turtle.onkeypress(yesil, "1")
turtle.onkeypress(acikyesil, "2")
turtle.onkeypress(mavi, "3")
turtle.onkeypress(acikmavi, "4")
turtle.onkeypress(sari, "5")
turtle.onkeypress(kirmizigul, "6")
turtle.listen()
when I try to run this game every hecking time a screen opens for like 0.1 second and closes
if you try to help it will be so good for me
I was expecting the screen was going to be remain open because it was in the books image but I was not expecting to see the screen for just 0.1 seconds
Use turtle.done() at the end of your code and the window will stay until you close it yourself.
The official python wiki page for turtle clearly states that:
(turtle.mainloop) Must be the last statement in a turtle graphics program. Must not be used if a script is run from within IDLE in -n mode (No subprocess) - for interactive use of turtle graphics.
Since your program lacks a call to the mainloop function, it closes as soon as it is runs. All you have to do is add a
turtle.mainloop()
turtle.done()
at the end of your program.
I hope this helps :)
i believe this is what you tried to do all you had to do is import screen and set the screen setup and update it:
import turtle
from turtle import Screen
import time
turtle.pensize(5)
turtle.bgcolor("black")
turtle.pencolor("white")
turtle.turtlesize(2,2,2)
screen= Screen()
screen.setup(600,600)
def ileri():
turtle.fd(5)
def geri():
turtle.backward(5)
def sag():
turtle.right(90)
turtle.fd(5)
turtle.left(90)
def sol():
turtle.left(90)
turtle.fd(5)
turtle.right(90)
def sagdon():
turtle.right(10)
def soldon():
turtle.left(10)
def siyah():
turtle.pencolor("black")
def yesil():
turtle.pencolor("green")
def acikyesil():
turtle.pencolor("lightgreen")
def mavi():
turtle.pencolor("blue")
def acikmavi():
turtle.pencolor("lightblue")
def sari():
turtle.pencolor("yellow")
def kirmizigul():
turtle.pencolor("red")
while(True):
screen.update()
time.sleep(0.07)
turtle.onkeypress(ileri, "w" or "Up")
turtle.onkeypress(geri, "s" or "Down")
turtle.onkeypress(sag, "d")
turtle.onkeypress(sol, "a")
turtle.onkeypress(sagdon, "Right")
turtle.onkeypress(soldon, "Left")
turtle.onkeypress(siyah, "0")
turtle.onkeypress(yesil, "1")
turtle.onkeypress(acikyesil, "2")
turtle.onkeypress(mavi, "3")
turtle.onkeypress(acikmavi, "4")
turtle.onkeypress(sari, "5")
turtle.onkeypress(kirmizigul, "6")
turtle.listen()
screen.exitonclick()
hope it was usefull to you and goodluck.

Scrollbar for a menu

Recently I started to work for a school project. This project has to be an app which is created using python.
Everything worked very well, without problems , but I have a blocking point now.
For the main menu of my app, I want to add a scrollbar in the right side of the interface.
This scrollbar will be used to navigate through photos, buttons and some labels.
This is the code:
import sys
print(sys.executable)
import tkinter as tk
from functools import partial
from tkinter import *
from tkinter import messagebox
from PIL import Image, ImageTk
from QRcodepage import QRcode
class ThePage():
def pageMain(self):
MainPageClass=tk.Toplevel()
MainPageClass.geometry('500x500')
MainPageClass.title('MainPage')
MainPageClass.resizable(0,0)
MainPageClass.configure(bg='#C97E48')
#create hamburger menu
def toggle_win():
f1=Frame(MainPageClass,width=300,height=500,bg='#262626')
f1.place(x=300,y=0)
#create the rest of the buttons
def bttn(x,y,text,bcolor,fcolor,cmd):
def on_entera(e):
myButton1['background']=bcolor #ffcc66
myButton1['foreground']='#ab6038' #000d33
def on_leavea(e):
myButton1['background']=fcolor
myButton1['foreground']='#262626'
myButton1=Button(f1,text=text,width=24,height=2,fg='#262626'
,border=0,bg=fcolor,activeforeground='#262626'
,activebackground=bcolor,command=cmd)
myButton1.bind("<Enter>",on_entera)
myButton1.bind("<Leave>",on_leavea)
myButton1.place(x=x,y=y)
def closeWindow():
#newvar=createlogin.tkLogin
#btn=Button(MainPageClass,command=newvar.withdraw)
#btn.pack()
pass
bttn(13,80,'HOME','#0f9d9a','#14c4c0',None)
bttn(13,140,'TRAINER','#0f9d9a','#14c4c0',None)
bttn(13,200,'NUTRITIONAL PLAN','#0fd9da','#14c4c0',None)
bttn(13,260,'PHYSICAL EVALUATION','#0fd9da','#14c4c0',None)
bttn(13,320,'CHOOSE GYM','#0fd9da','#14c4c0',None)
bttn(13,380,'LOG OUT','#0fd9da','#14c4c0',closeWindow)
def dele():
f1.destroy()
#global img2
#img2=ImageTk.PhotoImage(Image.open('x.png'))
Button(f1,text='X',command=dele).place(x=5,y=10)
#Creating header using Canva function
def code():
code=QRcode()
code.openQR()
w,h=(550,100)
canvas=tk.Canvas(MainPageClass,height=h,width=w)
canvas.pack()
bg=tk.PhotoImage(file="headerbackground.png")
bg_1=tk.Label(MainPageClass,image=bg)
bg_1.place()
Logo=Image.open('C:\Robert Andrei\Facultate\FEUP\Software Design\Source code\Logo2.png')
LogoResiz=Logo.resize((100,100))
LogoRend=ImageTk.PhotoImage(LogoResiz)
LogoLabel=Label(MainPageClass,image=LogoRend)
LogoLabel.place(relx=0,rely=0)
photoHamburger=PhotoImage(file=r"C:\Robert Andrei\Facultate\FEUP\Software Design\Source code\hamburger.png")
photoHamburgerResize=photoHamburger.subsample(7,7)
Hamburgerbtn=tk.Button(MainPageClass,image=photoHamburgerResize,command=toggle_win,text='Login',bd='0')
Hamburgerbtn.place(relx=0.9,rely=0.1,anchor=CENTER)
#This is the end of our code for the Canva area
sb = Scrollbar(MainPageClass,orient=VERTICAL)
sb.pack(side = RIGHT, fill ='y')
TitleLabel=tk.Label(MainPageClass,text='Welcome to your digital gym friend',bg="#C97E48",font='Helvetica 14 bold',xscrollcomand=sb.set)
TitleLabel.place(relx=0.18,rely=0.3)
QRbutton=tk.Button(MainPageClass,text='QR Code',bd='4',command=code,xscrollcomand=sb.set)
QRbutton.place(relx=0.45,rely=0.38)
photoYogaclass=PhotoImage(file=r"C:\Robert Andrei\Facultate\FEUP\Software Design\Source code\yoga.PNG")
photoYogaResize=photoYogaclass.subsample(2,2)
YogaLabel=tk.Label(MainPageClass,image=photoYogaResize,border=0,xscrollcomand=sb.set)
YogaLabel.place(relx=0.1,rely=0.5)
YogaText=tk.Label(MainPageClass,text='Yoga Class',border=0,bg='#C97E48', foreground='white',font=('Arial',14),xscrollcomand=sb.set)
YogaText.place(relx=0.13,rely=0.7)
photoJoin=PhotoImage(file=r'C:\Robert Andrei\Facultate\FEUP\Software Design\Source code\JoinButton.PNG')
photoJoinResize=photoJoin.subsample(1,1)
JoinButton=tk.Button(MainPageClass,image=photoJoinResize,command=None,bd='0',bg="#C97E48",xscrollcomand=sb.set)
JoinButton.place(relx=0.5,rely=0.5)
photoJogging=PhotoImage(file=r'C:\Robert Andrei\Facultate\FEUP\Software Design\Source code\Jogging.PNG')
photoJoggingResize=photoJogging.subsample(2,2)
JoggingLabel=tk.Label(MainPageClass,image=photoJoggingResize,border=0,xscrollcomand=sb.set)
JoggingLabel.place(relx=0.1,rely=0.8)
JoggingText=tk.Label(MainPageClass,text='Jogging Class',border=0,bg='#C97E48', foreground='white',font=('Arial',14),yscrollcomand=sb.set)
JoggingText.place(relx=0.13,rely=1.1)
mainloop()
Do you can help to create a scrollbar which will help me scrolling through the interface?
Thanks!!!!

Tkinter bind event isn't calling function

I have this code:
from tkinter import *
class logic():
def createComponent(self, event):
print("{0},{1}".format(event.x,event.y))
class gui(logic):
window = Tk()
obj = logic()
def initGui(self):
gui.window.mainloop()
def onClick(self):
gui.window.bind("<Button-1>",gui.obj.createComponent)
obj2 = gui()
obj2.initGui()
while True:
obj2.onClick()
In theory this code should print mouse coordinates on lmb click but "createComponent" isn't called for some reason (also no errors). What Im doing wrong?
Fixed the code:
window.mainloop() is already a loop putting it in while True breaks the code
The classes were setup wrong
from tkinter import *
window = Tk()
def createComponent(event):
print("{0},{1}".format(event.x,event.y))
window.bind("<Button-1>", createComponent)
window.mainloop()
OOP:
from tkinter import *
class windFuncs:
def createComponent(event):
print("{0},{1}".format(event.x,event.y))
class wind(Tk):
pass
window = wind()
window.bind("<Button-1>", windFuncs.createComponent)
window.mainloop()
You may wish to put createComponent in class wind

Tkinter canvas PhotoImage is not appearing

I have a problem with my code. I am creating a small video game called Lumanite. I have created the homepage and have started the graphics generation, but I have run into a bug. I am using Python 3.3 and am on a Win 10 laptop. I run the program through a run file, which accesses the main_game file that uses the classes outlined in a separate file, spritesclasses. I am trying to make a sprite appear. Here is the code for the main_game file and the spritesclasses file. (They import the canvas and root from a MENU file)
#SPRITES
from tkinter import *
from GUI_FILE import canvas, root
from OPENING_FILE import show, hide
class Sprite():
def __init__(self, photoplace):
self.orgin = photoplace
self.photo = PhotoImage(file=photoplace)
self.w = self.photo.width()
self.h = self.photo.height()
def draw(self):
self.sprite = canvas.create_image(self.h, self.w, image=self.photo)
And the MAIN_GAME file:
#Main Game File:
from tkinter import *
from OPENING_FILE import show, hide
from GUI_FILE import root, canvas
from spritesclasses import *
def start_game():
genterrain()
def genterrain():
test = Sprite("logo.gif")
test.draw()
And the sprites are not appearing. No error or anything. Please help me. I will supply you with information at a further notice.
This is a known but tricky issue. You can read about it in Why do my Tkinter images not appear? I've implemented one possible solution below:
from tkinter import *
class Sprite():
def __init__(self, photoplace):
self.photo = PhotoImage(file=photoplace)
self.w = self.photo.width()
self.h = self.photo.height()
self.sprite = None
def draw(self):
canvas = Canvas(root, width=self.w, height=self.h)
canvas.pack()
self.sprite = canvas.create_image(0, 0, anchor=NW, image=self.photo)
def start_game():
genterrain()
def genterrain():
sprite = Sprite("logo.gif")
sprite.draw()
sprites.append(sprite) # keep a reference!
root = Tk()
sprites = []
start_game()
root.mainloop()
The assignment self.photo = PhotoImage(file=photoplace) isn't a sufficient reference as the object test goes out of scope when genterrain() returns and is garbage collected, along with your image. You can test this by commenting out the line sprites.append(sprite) and see your image disappear again.
Also, it wasn't clear why you were positioning the image at it's own width and height -- the first to arguments to create_image() are the X and Y position. I moved canvas creation into draw() so I could size the canvas to the image but that's not a requirement of the visibility fix.

Python:Bad Window Path Name when using deiconify

I've been having this problem with a python program I am making where if I display a TopLevel window, in this case my Help Menu, then withdraw it then try to display it again I get the following error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:\Users\****\Documents\GitHub\ProjectName\ProjectName\GUI.py", line 60, in displayHelp
self.helpMenu.display();
File "C:\Users\****\Documents\GitHub\ProjectName\ProjectName\HelpMenu.py", line 35, in display
self.deiconify();
File "C:\Python34\lib\tkinter\__init__.py", line 1646, in wm_deiconify
return self.tk.call('wm', 'deiconify', self._w)
_tkinter.TclError: bad window path name ".60000336"
The error first happened when I was withdrawing from within HelpMenu.py and using deiconify to redisplay it from the GUI.py file.
Since then I have tried multiple ways to fix the problem including calling deiconify from within HelpMenu.py and updating the copy of help menu stored in the GUI when I withdraw it.
I am running Python 3.4.2
I have already done extensive searches online and failed to find a solution to my problem. I have found other mentions of this error but they either didn't relate to my situation or their solutions did not work.
Here is the entire code for the HelpMenu.py followed by an extract from GUI.py that retains the functionality to reproduce the error but has other code removed.
#!/usr/bin/python
try:
from Tkinter import *
except ImportError:
from tkinter import *
class HelpMenu(Toplevel):
def __init__(self, parent, observer):
Toplevel.__init__(self);
self.observer = observer;#Observer is the GUI, this is here just so I can update the GUI when I withdraw this window
self.setup();
self.withdraw();
self.protocol('WM_DELETE_WINDOW', self.quit());#Changes the close button to just hide the window
def setup(self):
self.columnconfigure(0,weight=1);
w = 400;#Sets up the window position on the screen
h = 150;
sw = self.winfo_screenwidth();
sh = self.winfo_screenheight();
x=(sw-w)/2;
y =(sh-h)/2;
self.update();
self.geometry('%dx%d+%d+%d' % (w,h,x,y));
self.resizable(width=0, height=0);
self.grid();
self.title("Help Menu");
def quit(self):#Hides the window
self.withdraw();
self.observer.updateHelp(self);
def display(self):#Re-displays the window
self.deiconify();
Here is code taken from GUI.py and modified to only have the code needed to reproduce the issue.
#!/usr/bin/python
#Allows compatibility with any version of Python by checking for both versions of Tkinter
try:
from Tkinter import *
except ImportError:
from tkinter import *
#Imports the AutoCompleteEntry
from HelpMenu import HelpMenu
class UI(Tk):
def initialize(self):
#Handles setting up most of the GUI
w = 500;#Window width
h = 500;#Window height
sw = self.winfo_screenwidth();#Gets screen width
sh = self.winfo_screenheight();#Gets screen height
x=(sw-w)/2;#Calculates the x position for the left side of the window that allows it to be placed in the center of the screen
y =(sh-h)/2;#Calculates the y position for the top of the window that allows it to be placed in the center of the screen
self.update();#Forces and update on the window
self.geometry('%dx%d+%d+%d' % (w,h,x,y));#Sets the windows width, height and position
self.minsize(int(w),int(h/2));#Sets the minimum size of the window
self.configureMenu();
def updateHelp(self, helpMenu):
self.helpMenu=helpMenu;
def displayHelp(self):
self.helpMenu.display();
def configureMenu(self):
#Handles configuring and setting up the menus
menu = Menu(self);#Setup the menu bar
menu.add_command(label="Help",command=self.displayHelp);
self.config(menu=menu);
def __init__(self, parent):
#Handles the initial call to create a GUI
Tk.__init__(self,parent);#Parent constructor
self.parent = parent;#Store the parent
self.initialize();#Initilize the GUI
self.helpMenu = HelpMenu(self, self);
self.mainloop();#Start the main loop
if __name__ == "__main__":
import sys
main = UI(None);
One last note, I am slightly new to Python, so there might be other errors in my code and while I wont mind if they get pointed out, the main focus I have right now is fixing this path name error.
EDIT:Almost a month now and I have still not found a solution to the problem. Any help would be great but at this point I am probably going to have to abandon my project.
So, after a break I went back to look at this problem again.
Turns out that the issue was self.protocol('WM_DELETE_WINDOW', self.quit()) was not actually calling self.quit() and was destroying the window completely.
A quick change to self.protocol('WM_DELETE_WINDOW', self.quit) seems to have fixed it.
I think maybe the comma causes the problem. Try write it like this:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
try:
from Tkinter import *
except ImportError:
from tkinter import *
class HelpMenu(Toplevel):
def __init__(self, parent, observer):
Toplevel.__init__(self)
self.observer = observer # Observer is the GUI, this is here just so I can update the GUI when I withdraw this window
self.setup()
self.withdraw()
self.protocol('WM_DELETE_WINDOW', self.quit()) # Changes the close button to just hide the window
def setup(self):
self.columnconfigure(0, weight=1)
w = 400 # Sets up the window position on the screen
h = 150
sw = self.winfo_screenwidth()
sh = self.winfo_screenheight()
x = (sw - w) / 2
y = (sh - h) / 2
self.update()
self.geometry('%dx%d+%d+%d' % (w, h, x, y))
self.resizable(width=0, height=0)
self.grid()
self.title("Help Menu")
def quit(self): # Hides the window
self.withdraw()
self.observer.updateHelp(self)
def display(self): # Re-displays the window
self.deiconify()
class UI(Tk):
def initialize(self):
# Handles setting up most of the GUI
w = 500 # Window width
h = 500 # Window height
sw = self.winfo_screenwidth() # Gets screen width
sh = self.winfo_screenheight() # Gets screen height
x = (sw - w) / 2 # Calculates the x position for the left side of the window that allows it to be placed in the center of the screen
y = (sh - h) / 2 # Calculates the y position for the top of the window that allows it to be placed in the center of the screen
self.update() # Forces and update on the window
self.geometry('%dx%d+%d+%d' % (w, h, x, y)) # Sets the windows width, height and position
self.minsize(int(w), int(h / 2)) # Sets the minimum size of the window
self.configureMenu()
def updateHelp(self, helpMenu):
self.helpMenu = helpMenu
def displayHelp(self):
self.helpMenu.display()
def configureMenu(self):
# Handles configuring and setting up the menus
menu = Menu(self) # Setup the menu bar
menu.add_command(label="Help", command=self.displayHelp)
self.config(menu=menu)
def __init__(self, parent):
# Handles the initial call to create a GUI
Tk.__init__(self, parent) # Parent constructor
self.parent = parent # Store the parent
self.initialize() # Initilize the GUI
self.helpMenu = HelpMenu(self, self)
self.mainloop() # Start the main loop
if __name__ == "__main__":
main = UI(None)
It works perfectly from myside.

Categories