NameError: name 'regc' is not defined in Tkinter - python

I got a name error when i am using this code.Can anyone fix this problem?
from tkinter import *
import mysql.connector
home=Tk()
home.geometry("700x700")
home.title("Home")
reg=Button(home,text="Register",bg='brown',fg='white',width=20,command=regc)
reg.place(x=350,y=200)
mainloop()
I got an error like this:
Traceback (most recent call last):
File "C:/Users/Softech/Desktop/tkinterproject.py", line 29, in <module>
reg=Button(home,text="Register",bg='brown',fg='white',width=20,command=regc)
NameError: name 'regc' is not defined

Maybe you forgot to define the function regc, anyway in the code its not there. So start off by defining it. Keep in mind, you have to define it before the declaration of the button.
from tkinter import *
import mysql.connector
def regc():
new=Toplevel()
new.geometry("500x500")
new.title("Registration")
Label_reg=Label(new,text="REGISTRATION FORM",width=20,font=("bold",20))
Label_reg.place(x=90,y=53)
lname=Label(new,text="Name",width=20,font=("bold",10))
lname.place(x=80,y=130)
home=Tk()
home.geometry("700x700")
home.title("Home")
reg=Button(home,text="Register",bg='brown',fg='white',width=20,command=regc)
reg.place(x=350,y=200)
home.mainloop()
To understand more on how to define a function, take a look here
Hope it helped you solve your error.
Cheers

Related

Is it possible to somehow write a def function in one file and use it in another if I import it?

I want to create an 'toolkit' that will define many functions for me, and then import it when I need it... here is what I mean.
# I'm naming this file 'EssentialToolkit'
def hello():
print ("Hello")
And in another file:
import EssentialToolKit
hello()
but I get this error:
Traceback (most recent call last):
File "C:\Users\vas71\AppData\Local\Programs\Python\Python38\tes.py", line 2, in <module>
hello()
NameError: name 'hello' is not defined
How do I solve this problem?
Thank you for helping!
Your other Python file does not know what hello is, you have to tell that you get it from EssentialToolKit
You can do as the following
import EssentialToolKit
EssentialToolKit.hello()
Or
from EssentialToolKit import hello
hello()

Using python function from other python file and subsequent class?

I have been learning working with classes in python after learning OOPs in c++.
I am working on a project, where I have a class defined in one file, and an important function to be used in the class in the seperate file.
I have to call the class in the first file, but I am getting the ImportError.
Great, if you could help.
try1.py
from try2 import prnt
class a:
def __init__(self):
print("started")
def func1(self):
print("func1")
prnt()
try2.py
from try1 import a
b = a()
b.func1()
def prnt():
b.func()
As for eg, in the above example, when I am running try1.py, I am getting an ImportError: cannot import name 'prnt'.
You absolutely need to redesign your project. Even if you did manage to get away with the cyclic imports (ie by moving the import to inside the function - but don't do it) you will still get a NameError: name 'b' is not defined since b is not define in prnt.
Unless prnt can't be defined in class a (why?), consider defining prnt in a third, "utils" file and import it in both try1.py and try2.py and pass an object to it so it can access all of its attributes.
Just run your code, read the error, and deduct something from it.
When you run it, here is the error message :
Traceback (most recent call last):
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
File "C:\Users\Kilian\Desktop\Code\Garbage\temp2.py", line 1, in <module>
from tmp import a
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
ImportError: cannot import name prnt
Your script is trying to import something it already has tried to import earlier on. Python is probably deducing that it can't import it. :)

Python Tkinter Error

I have tried to work with the Tkinter library, however, I keep getting this message, and I don't know how to solve it.. I looked over the net but found nothing to this specific error - I call the library like this:
from Tkinter import *
and I get this error -
TclError = Tkinter.TclError
AttributeError: 'module' object has no attribute 'TclError'
I have no clue what can I do now..
Thank you
full traceback:
Traceback (most recent call last):
File "C:/Users/Shoham/Desktop/MathSolvingProject/Solver.py", line 3, in <module>
from Tkinter import *
File "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\lib- tk\Tkinter.py", line 41, in <module>
TclError = Tkinter.TclError
AttributeError: 'module' object has no attribute 'TclError'
You imported (mostly) everything from the module with from Tkinter import *. That means that (mostly) everything in that module is now included in the global namespace, and you no longer have to include the module name when you refer to things from it. Thus, refer to Tkinter's TclError object as simply TclError instead of Tkinter.TclError.
The problem seems to be in "C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\lib-tk\Tkinter.py:
The regular python install imports in lib-tk\Tkinter.py are different to what is in PortablePython2.7.6.1\App\lib\lib-tk\Tkinter.py:
try:
import _tkinter
except ImportError, msg:
raise ImportError, str(msg) + ', please install the python-tk package'
tkinter = _tkinter # b/w compat for export
TclError = _tkinter.TclError
Then where Tkinter is used in PortablePython _tkinter is used instead. It seems like a bug in PortablePython.
The full contents of the file are here. Replacing the file in C:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\lib-tk\Tkinter.py as per the comments fixes the issue.
Like #ErezProductions said. You either have to import everything and access it directly or import only the module.
from Tkinter import *
TclError
or
import Tkinter
Tkinter.TclError
See the difference:
>>> import tkinter
>>> TclError = tkinter.TclError
>>>
No error. But, with your method:
>>> from tkinter import *
>>> TclError = tkinter.TclError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'tkinter' is not defined
The difference is that the first method imports the module tkinter into the name space. You can address its properties using the dot notation tinter.property. However, the from tkinter import * imports the module's properties into the name space, not the module itself.
Either try the first method given above, or adjust your approach (NB: importing all properties is a bad idea) like so:
>>> from tkinter import *
>>> my_TclError = TclError # renamed because TclError defined in tkinter
>>>

Fixed: Python NameError, fixed AttributeError and got this?

FIXED: turns out there is a module already called parser. Renamed it and its working fine! Thanks all.
I got a python NameError I can't figure out, got it after AttributeError. I've tried what I know, can't come up with anything.
main.py:
from random import *
from xml.dom import minidom
import parser
from parser import *
print("+---+ Roleplay Stat Reader +---+")
print("Load previous DAT file, or create new one (new/load file)")
IN=input()
splt = IN.split(' ')
if splt[0]=="new":
xmlwrite(splt[1])
else:
if len(splt[1])<2:
print("err")
else:
xmlread(splt[1])
ex=input("Press ENTER to Exit...")
parser.py:
from xml.dom import minidom
from random import *
def xmlread(doc):
xmldoc = minidom.parse(doc)
itemlist = xmldoc.getElementsByTagName('item')
for s in itemlist:
print(s.attributes['name'].value,":",s.attributes['value'].value)
def xmlwrite(doc):
print("no")
And no matter what I get the error:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 10, in <module>
xmlwrite.xmlwrite(splt[1])
NameError: name 'xmlread' is not defined
The same error occurs when trying to access xmlwrite.
When I change xmlread and xmlwrite to parser.xmlread and parser.xmlwrite I get:
Traceback (most recent call last):
File "K:\Python Programs\Stat Reader\main.py", line 15, in <module>
parser.xmlread(splt[1])
AttributeError: 'module' object has no attribute 'xmlread'
The drive is K:\ because it's my personal drive at my school.
If your file is really called parser.xml, that's your problem. It needs to be parser.py in order to work.
EDIT: Okay, since that wasn't your issue, it looks like you have a namespacing issue. You import your parser module twice when you use import parser and then from parser import *. The first form of it makes "parser" the namespace and the second form directly imports it, so in theory, you should have both parser.xmlwrite and xmlwrite in scope. It's also clearly not useful to import minidom in main.py since you don't use any minidom functionality in there.
If you clear up those and still have the issue, I would suggest looking at __ init __.py. If that still does nothing, it could just plain be a conflict with Python's parser module, you could substitute a name like myxmlparser.

Writing and importing custom modules/classes

I've got a class that I'm trying to write called dbObject and I'm trying to import it from a script in a different folder. My structure is as follows:
/var/www/html/py/testobj.py
/var/www/html/py/obj/dbObject.py
/var/www/html/py/obj/__init__.py
Now, __init__.py is an empty file. Here are the contents of dbObject.py:
class dbObject:
def __init__():
print "Constructor?"
def test():
print "Testing"
And here's the contents of testobj.py:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
import obj.dbObject
db = dbObject()
When I run this, I get:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
NameError: name 'dbObject' is not defined
I'm new to Python, so I'm very confused as to what I'm doing wrong. Could someone please point me in the right direction?
EDIT: Thanks to Martijn Pieters' answer I modified my testobj.py as follows:
#!/usr/bin/python
import sys
sys.path.append("/var/www/html/py")
sys.path.append("/var/www/html/py/dev")
from obj.dbObject import dbObject
db = dbObject()
However, now when I run it I get this error:
Traceback (most recent call last):
File "testobj.py", line 7, in <module>
db = dbObject()
TypeError: __init__() takes no arguments (1 given)
Is this referring to my init.py or the constructor within dbObject?
EDIT(2): Solved that one myself, the constructor must be able to take at least one parameter - a reference to itself. Simple fix. Looks like this problem is solved!
EDIT (Final): This is nice - I can cut out the import sys and sys.path.append lines and it still works in this instance. Lovely.
You need to import the class from the module:
from obj.dbObject import dbObject
This adds the class dbObject directly to your local namespace.
Your statement import obj.dbObject adds the name obj to the local namespace, so you could also do this instead:
db = obj.dbObject.dbObject()
because obj.dbObject is the dbObject.py module in your obj package directory.

Categories

Resources