'RawTurtle' object has no attribute 'Turtle' - python

I saw the sorting example in turtle demo which python includes and I would like to add similar animations in my program. My program is based in tkinter and I would like to insert turtle animations in a tkinter canvas (with RawTurtle) so first I tried to create a black box in the canvas and I get the following error message:
AttributeError: 'RawTurtle' object has no attribute 'Turtle'
Here's my code:
import tkinter
from turtle import *
class MyApp():
def __init__(self, parent):
self.p = parent
self.f = tkinter.Frame(self.p).pack()
self.c = tkinter.Canvas(self.f, height = '640', width = '1000')
self.c.pack()
self.t = RawTurtle(self.c)
self.main(5)
def main(self, size):
self.t.size = size
self.t.Turtle.__init__(self, shape="square", visible=False)
self.t.pu()
self.t.shapesize(5, 1.5, 2)
self.t.fillcolor('black')
self.t.st()
if __name__ == '__main__':
root= tkinter.Tk()
frame = MyApp(root)
root.mainloop()

You pretty much have it -- those two settings you were trying to change via the non-existent Turtle() instance method can be handled when creating the RawTurtle:
import tkinter
from turtle import RawTurtle
class MyApp():
def __init__(self, parent):
self.p = parent
self.f = tkinter.Frame(self.p).pack()
self.c = tkinter.Canvas(self.f, height=640, width=1000)
self.c.pack()
self.t = RawTurtle(self.c, shape='square', visible=False)
self.main(5)
def main(self, size):
self.t.size = size # does nothing if stamping with pen up
self.t.penup()
self.t.shapesize(5, 1.5, 2)
self.t.fillcolor('black') # the default
self.t.stamp()
if __name__ == '__main__':
root = tkinter.Tk()
frame = MyApp(root)
root.mainloop()

Related

tkinter- subclass of button not placing on screen from inside another class

I'm making a ide for brainf*ck in python using tkinter and I'm adding a recent projects section but when I'm placing the buttons they do not appear on the screen.
Here is the code for the Scene:
from tkinter import *
from tkinter import filedialog as File
import tkinter as tk
class HoverButton(tk.Button):
def __init__(self, master, **kw):
tk.Button.__init__(self, master=master, **kw)
self.defaultBackground = "#5d5d5d"
self['background'] = self.defaultBackground
self['activebackground'] = "#6d6d6d"
self.bind("<Enter>", self.on_enter)
self.bind("<Leave>", self.on_leave)
def on_enter(self, e):
self['background'] = "#6d6d6d"
def on_leave(self, e):
self['background'] = self.defaultBackground
class ProjectPage(Frame):
def __init__(self, master, projects=[]):
super().__init__(master)
self.projects = projects
self.buttons = []
self.mstr = self.master.master
self.title = "PesolIde: Projets"
self.width = 800
self.height = 500
self.color = "#4d4d4d"
self.projectFrame = tk.Frame(self.mstr,width=800,height=50,bg="#5d5d5d")
self.newProject = HoverButton(self.mstr,text="New Project", height=1, bg="#6d6d6d")
self.openProject = HoverButton(self.mstr,text="Open Project", height=1,bg="#6d6d6d", command=OpenAsk)
self.projectdisplay = tk.Frame(self.mstr, width=700, height=300, bg="#5d5d5d", highlightbackground="black", highlightthickness=1)
for i in range(len(self.projects)):
self.buttons.append(HoverButton(master, text=self.projects[i].split(':')[0], width=50, height=1))
if len(self.buttons)>=40:
break
self.loaded = False
def show(self):
self.projectFrame.place(x=0, y=0)
self.newProject.place(x=20, y=10)
self.openProject.place(x=120, y=10)
self.projectdisplay.place(x=50,y=100)
self.y = 100
print(len(self.buttons))
for i in range(len(self.buttons)):
print("placing " + str(self.buttons[i]))
self.buttons[i].place(x=50,y=100+(20*i))
self.master.set(title=self.title,width=self.width,height=self.height)
self.master.master['bg'] = self.color
def hide(self):
self.newProject.place_forget()
self.openProject.place_forget()
def load(self):
if not self.loaded:
self.newProject.place_forget()
self.openProject.place_forget()
self.loaded = True
def unload(self):
self.newProject.destroy()
self.openProject.destroy()
def OpenAsk():
name = File.askopenfilename()
and here is the code for main.py:
from tkinter import *
import src.framework.modules.Window.Window as windows
import src.framework.src.Scenes.all as Scenes
import tkinter as tk
root = tk.Tk()
window = windows.window(root, "", 800, 500)
window.place()
projects = open("projects.txt",'r').read().split("\n")
start = Scenes.ProjectPage.ProjectPage(window,projects)
start.show()
window.mainloop()
When I make a HoverButton outside the ProjectPage class in the ProjectPage file, it appears as expected but not when initialised from within the class of directly from the main file.
Here are some screenshots.
The output from running main.py:
The output from running from outside the ProjectPage class with the code on the left:
Try to insert values for relx, rely, relwidth, relheight as attributes in "place" or you can as well insert height, width as attributes for place.
Check out the documentation: https://www.tutorialspoint.com/python/tk_place.htm

Using pyopengltk and add another common tkinter function

I currently try to create opengl simulation in tkinter, so i found this. The example code provided there :
import time
import tkinter
from OpenGL import GL
from pyopengltk import OpenGLFrame
class AppOgl(OpenGLFrame):
def initgl(self):
"""Initalize gl states when the frame is created"""
GL.glViewport(0, 0, self.width, self.height)
GL.glClearColor(0.0, 1.0, 0.0, 0.0)
self.start = time.time()
self.nframes = 0
def redraw(self):
"""Render a single frame"""
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
tm = time.time() - self.start
self.nframes += 1
print("fps",self.nframes / tm, end="\r" )
if __name__ == '__main__':
root = tkinter.Tk()
app = AppOgl(root, width=320, height=200)
app.pack(fill=tkinter.BOTH, expand=tkinter.YES)
app.animate = 1
app.after(100, app.printContext)
app.mainloop()
I can run it fine but i sligthly confused because i usually use tkinter with this format :
class frontpage(tk.Tk):
def __init__(self,parent):
tk.Tk.__init__(self,parent)
self.parent=parent
'''Creating'''
#Window 1
label1 = tk.Label(self, text = 'App title',bg='blue',fg='white')
frame1 = tk.Frame(self)
''' Some code '''
label1.pack(fill='x')
frame1.pack()
def func1(self):
#some function
if __name__ == '__main__':
frontapp = frontpage(None)
frontapp.title('App v0.1')
frontapp.mainloop()
Given that, is there anyway i could insert normal tkinter item such as frame, button, etc using pyopengltk?
Based on solution suggested by #stovfl, we just need to insert our opengl class into our tkinter class __init__. Then it become :
from __future__ import print_function
import sys, math, time
import tkinter as tk
from OpenGL import GL, GLU
from pyopengltk import OpenGLFrame
class AppOgl(OpenGLFrame):
def initgl(self):
"""Initalize gl states when the frame is created"""
GL.glViewport(0, 0, self.width, self.height)
GL.glClearColor(0.0, 1.0, 0.0, 0.0)
self.start = time.time()
self.nframes = 0
def redraw(self):
"""Render a single frame"""
GL.glClear(GL.GL_COLOR_BUFFER_BIT)
tm = time.time() - self.start
self.nframes += 1
print("fps",self.nframes / tm, end="\r" )
class frontpage(tk.Tk):
def __init__(self,parent):
tk.Tk.__init__(self,parent)
self.parent=parent
open_gl_frame = AppOgl(self, width=320, height=200)
'''Creating'''
#Window 1
label1 = tk.Label(self, text = 'App title',bg='blue',fg='white')
frame1 = tk.Frame(self)
''' Some code '''
open_gl_frame.animate=1 #dont forget this, or your simulation would not animated
open_gl_frame.pack()
label1.pack(fill='x')
frame1.pack()
def func1(self):
pass
if __name__ == '__main__':
frontapp = frontpage(None)
frontapp.title('App v0.1')
frontapp.mainloop()

multiplying moving rectangles in python (tkinter)

I have two questions:
I want to make several rectangles, moving randomly. I am at a point where i
can do it with one rectangle but i don't get it how to multiply them.
I am a beginner so i have copied this example and modified it in my favor but i don't know exactly why i have to write everytime the "self" and the "init". It seems to be common to name those parameters in this manner.
I looked both questions up several times but didn't find a satisfying answer.
here the code:
from tkinter import *
from tkinter.ttk import *
from random import *
class simulation:
def __init__(self, anzahl, master = None):
self.master = master
self.canvas = Canvas(master, width= 2736, height= 1824)
self.rectangle = self.canvas.create_rectangle(500, 380, 515, 395, fill = "black")
self.canvas.pack()
self.movement()
def movement(self):
self.canvas.move(self.rectangle, randint(-10,10), randint(-10,10))
self.canvas.after(100, self.movement)
if __name__ == "__main__":
master = Tk()
master.title("Simulation")
simulation = simulation(master)
mainloop()
maybe this will help you, make an object for each player and the canvas packed ones in order not to hide other players ...
from tkinter import *
from random import *
class simulation:
def __init__(self, master , canvas , color):
self.master = master
self.canvas = canvas
self.rectangle = canvas.create_rectangle(500, 380, 515, 395, fill=color)
def movement(self):
canvas.move(self.rectangle, randint(-10,10), randint(-10,10))
self.canvas.after(100, self.movement)
if __name__ == "__main__":
master = Tk()
canvas = Canvas(master, width=2736, height=1824)
canvas.pack()
master.title("Simulation")
player1 = simulation(master, canvas,"red")
player2 = simulation(master,canvas, "black")
player1.movement()
player2.movement()
mainloop()

Tkinter - Images is not display

I am new on Tkinter. I was trying to display two images on my canvas but I couldn't. I tried to achieve this by creating two different files. One will contain all logic behind and the other one will handle the gui. Here is my code so far:
file1.py
from file2 import *
import tkinter as tk
import random
# global variables
w = 'initial'
class start_gui(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self,parent, *args, **kwargs)
# create canvas
self.canvas = tk.Canvas(parent, width=800, height=800, background="green")
self.canvas.pack()
c = Display(self.canvas)
c.current_play(w)
if __name__ == "__main__":
# create main window
root = tk.Tk()
root.geometry("800x800")
start_gui(root)
root.mainloop()
file2.py
import tkinter as tk
from functools import partial
from PIL import ImageTk
from PIL import Image
class Display:
def __init__(self, canv):
self.canvas = canv
def current_play(self, option):
if (option == 'initial'):
self.initial_display()
elif (option == 'n' or option == 's'):
self.ns_display()
def initial_display(self):
# display cat image
self.im = Image.open("cat.gif")
self.photo_image = ImageTk.PhotoImage(self.im)
self.demo = self.canvas.create_image(400, 400, image=self.photo_image, anchor='center')
self.canvas.create_rectangle(50, 25, 150, 75, fill="blue")
self.temp_image = tk.PhotoImage(file="cat.gif")
self.demo2 = self. canvas.create_image(600, 600, image = self.temp_image, anchor='center')
The problem here is that the two image items I created do not show up on the canvas but only the rectangle. Can someone help me with this?
PS: I am using python v 3.4
Another solution: We can make Display inherit from class tk.Canvas
import tkinter as tk
from PIL import ImageTk
from PIL import Image
import random
# global variables
w = 'initial'
class Display(tk.Canvas):
def __init__(self, parent, *args, **kwargs):
tk.Canvas.__init__(self, parent, *args, **kwargs)
def current_play(self, option):
if option == 'initial':
self.initial_display()
elif option == 'n' or option == 's':
self.ns_display()
def initial_display(self):
# display cat image
self.im = Image.open("cat.gif")
self.photo_image = ImageTk.PhotoImage(self.im)
self.demo = self.create_image(400, 400, image=self.photo_image, anchor='center')
self.create_rectangle(50, 25, 150, 75, fill="blue")
self.temp_image = tk.PhotoImage(file="cat.gif")
self.demo2 = self.create_image(600, 600, image = self.temp_image, anchor='center')
class start_gui(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self,parent, *args, **kwargs)
# create canvas
self.canvas = Display(parent, width=800, height=800, background="green")
self.canvas.pack()
self.canvas.current_play(w)
if __name__ == "__main__":
root = tk.Tk()
root.geometry("800x800")
start_gui(root)
root.mainloop()
The problem is one of garbage collection. Your Display object is stored in a local variable inside start_gui.__init__. Once start_gui is constructed, this object is thrown away. The image is an attribute of that object, so it gets garbage-collected. When an image object gets garbage-collected, tkinter is unable to display it.
The simple solution is to keep a permanent reference to Display:
self.display = Display(canvas)
self.display.current_play(w)

How to use graphics module and Tkinter module at the same time?

from Tkinter import *
root = Tk()
root.title("hello world")
root.geometry('300x200')
root.mainloop()
I want to use some function in Tkinter, while I am familiar with 'graphics'.
How can I use the function of graphics in this Tkinter window?
Here is the definition of Graphics.
# Graphics classes start here
class GraphWin(tk.Canvas):
"""A GraphWin is a toplevel window for displaying graphics."""
def __init__(self, title="Graphics Window",
width=200, height=200, autoflush=True):
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", self.close)
tk.Canvas.__init__(self, master, width=width, height=height)
self.master.title(title)
self.pack()
master.resizable(0,0)
self.foreground = "black"
self.items = []
self.mouseX = None
self.mouseY = None
self.bind("<Button-1>", self._onClick)
self.bind_all("<Key>", self._onKey)
self.height = height
self.width = width
self.autoflush = autoflush
self._mouseCallback = None
self.trans = None
self.closed = False
master.lift()
self.lastKey = ""
if autoflush: _root.update()
More is on the http://mcsp.wartburg.edu/zelle/python/graphics.py
The graphics.py library packages the GraphWin object as a toplevel window. If you want to intergrate a GraphWin into a tkinter window with other frames and wigets you need to modify the graphics.py library and remove the toplevel wrapper around the GraphWin class so that it can be treated as a tkinter Canvas. This means you will need to append the modified library in your source file or rename and import it appropriately.
Here is an example of how it could be done in an App that integrates a Graphwin and another tk.Frame in one root window called "root". I will not include the entire modified library here, only the modified GraphWin init method, but NOTE -- that alone isn't sufficient -- you will need to go through the rest of the GraphWin class and all of the classes and methods in the library that you want to use; Point, Oval etc.. and change every time you read "_root" to "self.master", and also any time you read "master" should now be "self.master" and any "self.update()" should be "self.master.update()" too.
You may decide that the update() method can be removed, as you can now call self.root.update() with your own self.pauseLength = time.sleep(pauseLength) from inside the yourApp class. All of the occurrences of _root.update() in the graphics classes' methods yourApp might call you will have changed to self.master.update(), so you'll see that inside the modified GraphWin class the self.master is then assigned the parameter root, which must now be provided when you instantiate a GraphWin as in this sample implementation.
###################### SAMPLE IMPLEMENTATION #######################
import tkinter as tk
class yourApp:
def __init__(self, yourParameters):
self.root= tk.Tk()
self.canvas = GraphWin(self.root, yourParameters)
self.canvas.pack
self.frameOfWidgets = tk.Frame(self.root, yourParameters)
self.frameOfWidgets.pack()
App = yourApp(yourParameters)
App.root.mainloop()
################## MODIFIED GRAPHWIN CLASS #######################
class GraphWin(tk.Canvas):
"""A GraphWin is no longer in a toplevel wrapper and can be treated like a tk.Canvas in the parent window called root."""`
def __init__(self, root, title="Graphics Window",
width=200, height=200, borderwidth=0, autoflush=True):
self.master = root
self.master.protocol("WM_DELETE_WINDOW", self.close)
tk.Canvas.__init__(self, self.master, width=width, height=height, borderwidth=borderwidth)
self.master.title(title)
self.pack()
self.master.resizable(0, 0)
self.foreground = "black"
self.items = []
self.mouseX = None
self.mouseY = None
self.bind("<Button-1>", self._onClick)
self.bind_all("<Key>", self._onKey)
self.height = height
self.width = width
self.autoflush = autoflush
self._mouseCallback = None
self.trans = None
self.closed = False
self.lastKey = ""

Categories

Resources