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.
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.
I'm trying to get the names of my top 3 artists of last week with pylast (https://github.com/pylast/pylast) but I run into an error or get I get None as a result and I don't see what I'm doing wrong. pylast is a Python interface to Last.fm.
My code:
import pylast
API_KEY = ""
API_SECRET = ""
username = ""
password_hash = pylast.md5("")
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET, username=username, password_hash=password_hash)
user = network.get_authenticated_user();
weekly_artists = user.get_weekly_artist_charts();
# Keep the first three artists.
del weekly_artists[3:]
# Print the artist name and number of songs(weight).
for weekly_artist in weekly_artists:
artist,weight = weekly_artist
print (artist.get_name())
print (artist.get_correction())
artist.get_name() returns
None
artist.get_correction() returns
Traceback (most recent call last):
File "G:\projects\python\lastfm_weekly\lastfm-weekly.py", line 28, in <module>
print (artist.get_correction())
File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 1585, in get_correction
self._request(self.ws_prefix + ".getCorrection"), "name")
File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 1029, in _request
return _Request(self.network, method_name, params).execute(cacheable)
File "C:\Users\..\Python\Python36-32\lib\site-packages\pylast\__init__.py", line 744, in __init__
network._get_ws_auth()
AttributeError: 'str' object has no attribute '_get_ws_auth'
What am I doing wrong?
Here is a quick and dirty solution, i'm sure someone will provide something better but i just installed the package to test and it works.
network = pylast.LastFMNetwork(api_key=API_KEY, api_secret=API_SECRET)
artists = network.get_top_artists()
del artists[:3]
for i in artists:
artist, weight = i
print('Artist = {}. Weight = {}'.format(artist, weight))
I'm not really familiar with the package, I just installed it to help out with this but I do wonder what "get_name()" and "get_correction()" are as they're not in your provided code.
If they're not functions you created / are defined within your code then I'd look there for the problem.
Also, you're authenticating the user but the documentation explicitly states you don't need to unless you're writing data.
I am fairly new to python and with the help of tutorials I am trying to create a calculator but got stuck due to an error which I am unable to correct which occurs when I press a number button
from tkinter import *
root=Tk()
root.title("Yuvi's CAl")
global char
class cal():
def __init__(self):
self.string= StringVar()
root=Tk()
root.title("Yuvi's CAl")
self.string=StringVar
enter=Entry(root,textvariable=self.string)
enter.grid(row=0,column=0,columnspan=6)
values=["1","2","3","4","5","+","6","7","=","8","9","c"]
row=1
col=0
i=0
for txt in values:
if i==3:
row=3
col=0
if i==6:
row=4
col=0
if i==9:
row=5
col=0
if txt=="+":
but=Button(root,text=txt)
but.grid(row=row,column=col)
elif txt=="=":
but=Button(root,text=txt,command=lambda:self.equals)
but.grid(row=row,column=col)
elif txt=="c":
but=Button(root,text=txt,command=lambda:self.clr)
but.grid(row=row,column=col)
else:
but=Button(root,text=txt,command=lambda txt=txt:self.add(txt))
but.grid(row=row,column=col)
col+=1
i+=1
def add(self,char):
meet=self.string.get(self)
self.string.set((str(meet)) + (str(char)))
def equals(self):
result=eval(self.string.get())
self.string.set(result)
def clr(self):
self.string.set("")
ent=cal()
root.mainloop()
and this being the error when I press a number button
Traceback (most recent call last):
File "/usr/lib/python3.4/tkinter/__init__.py", line 1541, in __call__
return self.func(*args)
File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Misiio_calcuator.py", line 40, in <lambda>
but=Button(root,text=txt,command=lambda txt=txt:self.add(txt))
File "/home/yuvi/Documents/LiClipse Workspace/GUI/src/Misiio_calcuator.py", line 46, in add
meet=self.string.get(self)
File "/usr/lib/python3.4/tkinter/__init__.py", line 339, in get
value = self._tk.globalgetvar(self._name)
AttributeError: 'cal' object has no attribute '_tk'
Do rectify if any mistakes
Thank you in advance
There are several issues with your code first you should remove hiding your global vars within your __init__ as it creates two windows and only running mainloop for one of them. In addition you overwrite self.string with the StringVar class object after first creating an instance of it. So your __init__ could look like so
...
def __init__(self):
self.string=StringVar()
enter=Entry(root,textvariable=self.string)
enter.grid(row=0,column=0,columnspan=6)
values=["1","2","3","4","5","+","6","7","=","8","9","c"]
row=1
col=0
i=0
...
then in your add you don't have to pass self to self.string.get, that is it should look like
...
def add(self,char):
meet=self.string.get()
self.string.set((str(meet)) + (str(char)))
...
Those changes fixes your exception but I guess there are still other logical mistakes in the calculator, however that's not what the question is about and fixing them wouldn't help you learning python.
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