I've been trying to get my Tkinter wrapper (specialised to make a game out of) to work, but it keeps throwing up an error when it tries to draw a rectangle.
Traceback:
Traceback (most recent call last):
File "C:\Users\William\Dropbox\IT\Thor\test.py", line 7, in <module>
aRectangle = thorElements.GameElement(pling,rectangleTup=(True,295,195,305,205,"blue"))
File "C:\Users\William\Dropbox\IT\Thor\thorElements.py", line 79, in __init__
self.rectangle = self.area.drawRectangle(self)
File "C:\Python33\lib\tkinter\__init__.py", line 1867, in __getattr__
return getattr(self.tk, attr)
AttributeError: 'tkapp' object has no attribute 'drawRectangle'
The sections of the code that are relevant to the question,
class GameElement():
def __init__(self,area,rectangleTup=(False,12,12,32,32,"red")):
self.area = area
self.lineTup = lineTup #Tuple containing all the data needed to create a line
if self.lineTup[0] == True:
self.kind = "Line"
self.xPos = self.lineTup[1]
self.yPos = self.lineTup[2]
self.line = self.area.drawLine(self)
And here's the actual method that draws the rectangle onto the canvas (in the class that manages the Canvas widget), earlier in the same file:
class Area():
def drawLine(self,line):
topX = line.lineTup[1]
topY = line.lineTup[2]
botX = line.lineTup[3]
botY = line.lineTup[4]
colour = line.lineTup[5]
dashTuple = (line.lineTup[6][0],line.lineTup[6][1])
return self.canvas.create_line(topX,topY,botX,botY,fill=colour,dash=dashTuple)
print("Drew Line")
All input is greatly appreciated.
The error message is meant to be self explanatory. When it says AttributeError: 'tkapp' object has no attribute 'drawRectangle', it means that you are trying to do tkapp.drawRectangle or tkapp.drawRectangle(...), but tkapp doesn't have an attribute or method named drawRectangle.
Since your code doesn't show where you create tkapp or how you created it, or where you call drawRectangle, it's impossible for us to know what the root of the problem is. Most likely it's one of the following:
tkapp isn't what you think it is
you have a typo, and meant to call drawLine rather than drawRectangle,
you intended to implement drawRectangle but didn't
Related
My code:
from tkinter import *
from tkinter.ttk import Combobox
import random
screen = Tk()
screen.title("Password Generator")
screen.geometry('600x400')
screen.configure(background ="gray")
def Password_Gen():
global sc1
sc1.set("")
passw=""
length=int(c1.get())
lowercase='abcdefghijklmnopqrstuvwxyz'
uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'+lowercase
mixs='0123456789'+lowercase+uppercase+'##$%&*'
if c2.get()=='Low Strength':
for i in range(0,length):
passw=passw+random.choice(lowercase)
sc1.set(passw)
elif c2.get()=='Medium Strength':
for i in range(0,length):
passw=passw+random.choice(uppercase)
sc1.set(passw)
elif c2.get()=='High Strength':
for i in range(0,length):
passw=passw+random.choice(mixs)
sc1.set(passw)
sc1=StringVar('')
t1=Label(screen,text='Password Generator',font=('Arial',25),fg='green',background ="gray")
t1.place(x=60,y=0)
t2=Label(screen,text='Password:',font=('Arial',14),background ="gray")
t2.place(x=145,y=90)
il=Entry(screen,font=('Arial',14),textvariable=sc1)
il.place(x=270,y=90)
t3=Label(screen,text='Length: ',font=('Arial',14),background ="gray")
t3.place(x=145,y=120)
t4=Label(screen,text='Strength:',font=('Arial',14),background ="gray")
t4.place(x=145,y=155)
c1=Entry(screen,font=('Arial',14),width=10)
c1.place(x=230,y=120)
c2=Combobox(screen,font=('Arial',14),width=15)
c2['values']=('Low Strength','Medium Strength','High Strength')
c2.current(1)
c2.place(x=237,y=155)
b=Button(screen,text='Generate!',font=('Arial',14),fg='green',background ="gray",command=gen)
b.place(x=230,y=195)
screen.mainloop()
For some reason I'm keep getting those errors:
Traceback (most recent call last):
File "C:\Users\z\3D Objects\birthday\passwordgeneratorgui.py", line 32, in <module>
sc1=StringVar('')
File "C:\Users\z\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 540, in __init__
Variable.__init__(self, master, value, name)
File "C:\Users\z\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 372, in __init__
self._root = master._root()
AttributeError: 'str' object has no attribute '_root'
How can I fix those errors?
This is because the first argument to StringVar should be the "container". You are passing in an empty string instead of that. Replace the line sc1=StringVar('') with sc1=StringVar(). You can also read a guide to StringVars like this one: https://www.pythontutorial.net/tkinter/tkinter-stringvar/
Another mistake in your code is in this line:
b=Button(screen,text='Generate!',font=('Arial',14),fg='green',background ="gray",command=gen)
The problem is that you are passing in a function gen, which doesn't exist. I guess that you want to call the function Password_Gen with this button. So, replace it with this line:
b=Button(screen,text='Generate!',font=('Arial',14),fg='green',background ="gray",command=Password_Gen)
EDIT:
I have also noticed a minor problem with your password generator.
lowercase='abcdefghijklmnopqrstuvwxyz'
uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'+lowercase
mixs='0123456789'+lowercase+uppercase+'##$%&*'
In the mixs variable, there will be lowercase letters twice, I don't think you want this. I think what you want is this (because lowercase letters are already included in your uppercase variable):
mixs='0123456789'+uppercase+'##$%&*'
class Student:
def __init__(self,first,last,id):
self._first_name = first
self._last_name = last
self._id_number = id
self._enrolled_in = []
def enroll_in_course(self,course):
self._enrolled_in.append(course)
return self._enrolled_in()
s1 = Student("kathy","lor","323232")
s1.enroll_in_course("hello")
print(s1._enrolled_in)
In the code above, i am getting the error as:
Traceback (most recent call last):
File "main.py", line 14, in
s1.enroll_in_course("hello") File "main.py", line 10, in enroll_in_course
return self._enrolled_in()
TypeError: 'list' object is not callable
I am trying to solve the error, but unable to do so. Can anybody help me here.
You have defined self._enrolled_in but you're adding it to self.enrolled_in
Missed the underscore (self._enrolled_in.append)
You have called the attribute _enrolled_in in your __init__() method. In the enroll_in_course() method you're trying to append to enrolled_in which does not exist. So try by adding the underscore in front.
You are missing an _ in the appended statement. You should write self._enrolled_in.append(course) on your enroll_in_course method.
This code is part of a bigger program that uses the google Sheets API to get data from a cloud database (not really relevant, but a bit of context never hurt!)
I have this black of code in one python file named 'oop.py'
class SetupClassroom:
def __init__(self, arraynumber='undefined', tkroot='undefined'):
self.arraynumber = arraynumber
self.tkroot = tkroot
def setarraynumber(self, number):
from GUI_Stage_3 import showclassroom
self.arraynumber = number
print ('set array number:', number)
showclassroom()
def settkroot(self, tkrootinput):
self.tkroot = tkrootinput
self.tkroot has been assigned by another part of the code. This bit works, as I have already tested that it is being assigned, however, when I call 'self.tkroot' in another another file like this
def showclassroom():
from oop import SetupClassroom
username = current_user.username
classnumber = getnumberofuserclassrooms(username)
if SetupClassroom.arraynumber > classnumber:
errorwindow('you are not enrolled in that many classrooms!')
else:
classtoget = SetupClassroom.arraynumber
print('classtoget:', classtoget)
root = SetupClassroom.tkroot
name_label = Label(root, text=classtoget)
getclassroom(username, classtoget)
SetupClassroom = SetupClassroom
I get this error
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/GUI_Stage2_better.py", line 176, in <lambda>
l0 = ttk.Button(teacher_root, text=button0text, command=lambda: (SetupClassroom.setarraynumber(SetupClassroom, number=button0text), SetupClassroom.settkroot(SetupClassroom, 'teacher_root')))
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/oop.py", line 99, in setarraynumber
showclassroom()
File "/Users/jonathansalmon/PycharmProjects/Coursework_GUI/GUI_Stage_3.py", line 29, in showclassroom
root = SetupClassroom.tkroot
AttributeError: type object 'SetupClassroom' has no attribute 'tkroot'
I tried setting it up in the python console and it worked, so I have no idea what the problem is.
If anyone could help, it would be very much appreciated
Thanks!
John
You should create an instance of class, it will create the attribute in __init__, self.tkroot is the attribute of instance not class:
setupClassroom = SetupClassroom()
print(setupClassroom.tkroot)
Hope that will help you.
I am transforming a point from source frame to target frame using tf2. Below is the code snippet:
import tf2_ros
import tf2_geometry_msgs
transform = tf_buffer.lookup_transform(target_frame, source_frame, rospy.Time(0), rospy.Duration(1.0))
pose_transformed = tf2_geometry_msgs.do_transform_point(point_wrt_kinect, transform)
print pose_transformed
The code throws following error:
Traceback (most recent call last):
File "q1.py", line 29, in <module>
pose_transformed = tf2_geometry_msgs.do_transform_point(point_wrt_kinect, transform)
File "/opt/ros/indigo/lib/python2.7/dist-packages/tf2_geometry_msgs/tf2_geometry_msgs.py", line 59, in do_transform_point
p = transform_to_kdl(transform) * PyKDL.Vector(point.point.x, point.point.y, point.point.z)
AttributeError: 'Point' object has no attribute 'point'
The tf_geometry_msgs.py can be seen online at here. This seems silly as they are calling point.point.x.
Which point are they talking about? I believe it should be geometry_msgs/Point, which I declared in the following way:
from geometry_msgs.msg import Point
point_wrt_kinect = Point()
point_wrt_kinect.x = -0.41
point_wrt_kinect.y = -0.13
point_wrt_kinect.z = 0.77
Any workaround, please?
do_transform_point(point_wrt_kinect, transform)
point_wrt_kinect is the object of Point class. In documentation it should be PointStamped class object. its the error of documentation.
you have to create object of PointStamped class instead of Point class.
Im currently in an intro coding class and for my final project, i am trying to learn the pyglet module to create a game with a picture in the background, and have a character on the left that a user can make jump, and then have jumps come from the right at a set speed that the user will jump over. i need to use classes for the assignment, and im really having a hard time using creating a sprite class. heres my current code:
import pyglet
window = pyglet.window.Window(700,700)
image = pyglet.image.load('IMG_3315.jpg')#use 10x10 in. image
#image_2 = pyglet.image.load('IMG_3559.jpg')
main_batch = pyglet.graphics.Batch()
score_label = pyglet.text.Label(text="Score: 0", x=570, y=650, batch=main_batch)
the_jump = pyglet.image.load("jumpsi.png")
#horse = pyglet.sprite.Sprite(image_2, x = 50, y = 50)
# background_sound = pyglet.media.load(
# 'Documents/Leave The Night On.mp3',
# streaming=False)
class Jump(pyglet.sprite.Sprite):
def __init__(self, img, x=0, y=0, blend_src=770, blend_dest=771, batch=None, group=None, usage='dynamic', subpixel=False):
self.img = the_jump
self.x = 50
self.y = 50
def draw(self):
self.draw()
# verticle = Jump('verticle')
#window.event
def on_draw():
window.clear()
image.blit(0, 0)
main_batch.draw()
window = Jump()
#horse.draw()
#background_sound.play()
if __name__ == "__main__":
sprite = Jump()
pyglet.app.run()
i know its probably wrong but everything else i have tried (using preexisting games as examples) hasn't worked either.
my current error message is:
Traceback (most recent call last):
File "jumper.py", line 39, in <module>
sprite = Jump()
TypeError: __init__() takes at least 2 arguments (1 given)
im just really stuck and have been trying to figure this out for hours and not made any leeway. any help you can offer would be greatly appreciated. Thanks so much!
UPDATE: i recently changed the code, noticing the problem that Gustav pointed out, and change the end call to
if __name__ == "__main__":
sprite = Jump(the_jump)
pyglet.app.run()
but now i get the error
Traceback (most recent call last):
File "jumper.py", line 39, in <module>
sprite = Jump(the_jump)
File "jumper.py", line 21, in __init__
self.x = 50
File "/Library/Python/2.7/site-packages/pyglet/sprite.py", line 459, in _set_x
self._update_position()
File "/Library/Python/2.7/site-packages/pyglet/sprite.py", line 393, in _update_position
img = self._texture
AttributeError: 'Jump' object has no attribute '_texture'
The error message is telling you exactly which line the error is in and exactly what is wrong. You are initializing the Jump class without passing in an argument for the required parameter img.
You can fix this by either changing the initialization method or your call to Jump().
Here's an example for how to read Python's traceback.