global name 'display' is not found - python

I'm currently designing a code for a troubleshooter. My problem is that when I press "other", there should be a data entry form label, which there is. But when i type something into it and press continue, it shows an error that says "
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1482, in __call__
return self.func(*args)
File"R:\ICT\ControlledAssessment_15_17\Computing\Unit3\RiddhiSharma\FinalTroubleshooter.py", line 15, in click
display.insert(END, key)
NameError: global name 'display' is not defined
I think the problem in my actual code is here:
def click():
display.insert(END, key)
output.delete(0.0, END)
try:
entered_text=entry.get()
definition = my_glossary[entered_text]
except:
definition = "There is no entry for this word."
output.insert(END, definition)

Apparently display is not part of the tkinter module or it is not defined altogether. So when you try to use it, it raises an error because you have not defined display as a variable, function, class etc. So define display is a function that takes two arguments, END and key.
When defining display. You could do something like this:
display = 123
You could also make it a ENTRY, or whatever display is supposed to be. In your case, display doesn't have to be equal to 123. It could be equal to a class:
display = Display()
Just define Display() first... but display can be anything you want, as long you define it and use it correctly.

#PythonMaster thanks a lot for your help. To solve my problem I replaced the display function and wrote the code out like this:
def click():
entered_text = entry.get()
output.delete(0.0, END)
try:
definition = my_glossary[entered_text]
except:
definition = "There is no entry for this word."
output.insert(END, definition)

Related

curselection() missing 1 required positional argument: 'self'

lbox = Listbox
def Show():
Selected=lbox.get(lbox.curselection())
with open("pass.json","r+") as jfile:
try:
data=json.load(jfile)
for i in data['Details']:
if Selected==i["Site"]:
password_text.set(i["Password"])
uname_text.set(i["Username"])
except JSONDecodeError:
pass
I wanted to use curselection() but curselection() missing 1 required positional argument: 'self' is coming all the time
lbox was declared in another function which is given below
def Show_fun():
newWindow=Toplevel(window)
newWindow.title("Show your stuff")
newWindow.geometry("600x400")
Label(newWindow,text="Show passwords").grid(row=0,column=1,pady=10)
Label(newWindow,text="Site name : ").grid(row=1,pady=10)
lbox=Listbox(newWindow)
lbox.grid(row=1,column=2)
sites=[]
with open("pass.json","r+") as jfile:
try:
data=json.load(jfile)
for i in data['Details']:
sites.append(i["Site"])
except JSONDecodeError:
pass
lbox.config(height=lbox.size())
for i in sites:
lbox.insert(lbox.size(),i)
#site_entry = Entry(newWindow,textvariable = site_text,width=20,state=DISABLED).grid(row=1,column=2)
Label(newWindow,text="Username : ").grid(row=2,pady=10)
uname_entry=Entry(newWindow,textvariable=uname_text,state=DISABLED).grid(row=2,column=2)
Label(newWindow,text="Password : ").grid(row=3,pady=10)
pasword_entry=Entry(newWindow,textvariable=password_text,width=20,state=DISABLED).grid(row=3,column=2)
Button(newWindow,text="Show",command=Show,fg="#00FF00",bg="black",pady=10).grid(row=4,column=1)
I saw many YT vids . ListBox was working globally but in my its not working globally
EDIT: after giving parenthesis to ListBox() New error arises
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1895, in __call__
return self.func(*args)
File "d:/Python files/cybersecurity/password manager/password_test.py", line 24, in Show
Selected=lbox.get(lbox.curselection())
File "C:\Program Files\Python38\l`enter code here`ib\tkinter\__init__.py", line 3190, in get
return self.tk.call(self._w, 'get', first)
_tkinter.TclError: bad listbox index "": must be active, anchor, end, #x,y, or a number
The error message simply means that the method was not invoked on the object but on the class instead. In the first code snippet, you didn't seem to instantiate a ListBox object.
You must change the line
lbox = Listbox
to something like:
# Tkinter window object
window = Tk()
# Create ListBox object and bind to the Tkinter window
lbox = Listbox(window)
In the above snippet, an instance of ListBox is created on which the method curselection() could be called. Give more emphasis to the argument passed to ListBox. The window variable used above is an instance of the Tk class which essentially constructs the Tkinter window. Without this argument, the listbox widget won't know which window it must bind to.

No error...search function still not working

I made a code for a program that will show pictures that are accessible from the main menu. In my menu, there is a search option that opens a new window in which you can search through the database (that's a list) and if the entered words are in the list it will activate a function. the search function is shown in this part of code:
def search():
def compare(words):
key=words.get()
print(key)
for i in base:
if i==key:
if key=="apple":
AppleFunction()
if key=="pear":
PearFunction()
else:
messagebox.showerror("Eror!","Wrong entry, please correct!")
return
searchWindow=Toplevel(main)
searchWindow.geometry("425x125+225+145")
searchWindow.resizable(False,False)
searchWindow.config(bg=mycolor)
searchWindow.title("Search")
searchWindow.iconbitmap(r"f.ico")
words=Entry(searchWindow)
words.config(font="Times", width=20)
text1=Label(searchWindow, text="Search by key words:", wraplength=250, justify="center")
text1.pack(pady=5)
text1.config(bg=mycolor, font="Times")
words.pack(pady=5)
picture1=PhotoImage(file="ttt.gif")
searchButton=Button(searchWindow, image=picture1, height=19)
searchButton.config(bg=mycolor)
searchButton.bind("<Button>", compare(words))
searchButton.pack(pady=5)
searchWindow.mainloop()
return
It is all made with Tkinter module. I tried with global variables and arguments with functions, but there was no error. Although there is no error, the program still doesn't work. Can someone help me solve the problem?
So, I solved the problem by making the Entry global and giving the inner function that compares the strings the "event" argument. Here is the correct code:
def search():
def compare(event):
key=str(words.get())
for i in base:
if i==key:
if key=="Apple":
AppleFunction()
elif key=="Pear":
PearFunction()
else:
messagebox.showerror("Error!","Wrong entry, please correct!")
return
searchWindow=Toplevel(main)
searchWindow.geometry("425x125+225+145")
searchWindow.resizable(False,False)
searchWindow.config(bg=mycolor)
searchWindow.title("Tražilica")
searchWindow.iconbitmap(r"f.ico")
text1=Label(searchWindow, text="Search by key words:", wraplength=250, justify="center")
text1.pack(pady=5)
text1.config(bg=mycolor, font="Times")
global words
words=Entry(searchWindow)
words.config(font="Times", width=20)
words.pack(pady=5)
picture1=PhotoImage(file="ttt.gif")
searchButtton=Button(searchWindow, image=picture1, height=19)
searchButtton.config(bg=mycolor)
searchButtton.bind("<Button>", trazi)
searchButttonb.pack(pady=5)
searchWindow.mainloop()
return
Although, when I exit the program, it shows me the error message that I created for a case when the string doesn't match and opens a random new empty Tkinter window which shouldn't be happening because while the program was running it has found by keywords correctly what I was looking for and gave me the correct picture. Also, There was this error on the Console (but not in Shell):
invalid command name ".!toplevel.!button"
while executing
"$w cget -relief"
(procedure "tk::ButtonDown" line 9)
invoked from within
"tk::ButtonDown .!toplevel.!button"
(command bound to event)

root.after unable to find function_name

I am trying to put together a GUI that would read from a continuously updated TXT file and updated every once in a while. So far I succeeded with the first part and I am failing to use 'root.after()' to loop the whole thing but it results in NameError:
import tkinter as tk
root = tk.Tk()
class App:
def __init__(self, root):
frame = tk.Frame(root)
frame.pack()
iAutoInEN = 0
iAvailableEN = 0
self.tkAutoInEN = tk.StringVar()
self.tkAutoInEN.set(iAutoInEN)
self.tbAutoInEN = tk.Label(root, textvariable=self.tkAutoInEN)
self.tbAutoInEN.pack(side=tk.LEFT)
self.button = tk.Button(frame, text="Start", fg="red",
command=self.get_text)
self.button.pack(side=tk.LEFT)
def get_text(self):
fText = open("report.txt") #open a text file in the same folder
sContents = fText.read() #read the contents
fText.close()
# omitted working code that parses the text to lines and lines
# to items and marks them with numbers based on which they are
# allocated to a variable
if iLineCounter == 1 and iItemCounter == 3:
iAutoInEN = int(sItem)
self.tkAutoInEN.set(iAutoInEN)
root.after(1000,root,get_text(self))
app = App(root)
root.mainloop()
try:
root.destroy() # optional; see description below
except:
pass
The first instance runs without any problems and updates the value from 0 to the number in the TXT file but is accompanied with an error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\...\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:/.../pythonlab/GUI3.py", line 117, in get_text
self.after(1000,root,get_text())
NameError: name 'get_text' is not defined
EDIT:
When changed to the recommended "self.after(1000,self.get_text)"
class App:
...
def get_text(self):
fText = open("report.txt") #open a text file in the same folder
sContents = fText.read() #read the contents
fText.close()
# omitted code
if iLineCounter == 1 and iItemCounter == 3:
iAutoInEN = int(sItem)
self.tkAutoInEN.set(iAutoInEN)
self.after(1000,self.get_text)
Error changes
Traceback (most recent call last):
File "C:/.../pythonlab/GUI3.py", line 6, in <module>
class App:
File "C:/.../pythonlab/GUI3.py", line 117, in App
self.after(1000, self.get_text)
NameError: name 'self' is not defined
Also please consider this is my very first programme (not only) in Python, so I would appreciate if you are a little bit more explicit with your answers (e.g. when pointing out an indentation error, please refer to an exact line of code).
Because get_text is a method of App class you should call it as self.get_text.
After is a tkinter method. In that case you should call it as root.after. And self refers to the class you are in. So because get_text is a method of current class you should call is with self which is like this in other programming languages like Java.
...
root.after(1000, self.get_text)
...
Firstly, like James commented, you should fix your indentation so that the functions are a part of the class.
Then, change this line
root.after(1000,root,get_text(self))
to this
root.after(1000, self.get_text)
Check out the answer to the following question, which uses the code I just gave you:
Tkinter, executing functions over time

Python function not defined when it should be?

I've looked around and don't really know what else to do. My function is not defined after the place where I call it. I'm thinking its probably something stupid, but I can't find it.
def function1():
global tobegrouped
if(len(tobegrouped) >= 2):
print(len(tobegrouped))
prs1 = random.choice(tobegrouped)
print("got prs1")
prs2 = random.choice(tobegrouped)
print("got prs2")
newgroup = group(prs1, prs2)
print("made group")
global groups
groups.append(newgroup)
print("appended to group")
newgroup.send_message("Welcome to robinbot, have fun, and don't spam", self)
else :
print("no group ready yet")
And this is where I'm calling it. I've already checked that its past the definition of the function in the file.
if command == '/start':
# MAYBE CHECK IF IN GROUP HERE
global tobegrouped
tobegrouped.append(chat_id)
print("in to be grouped")
self.sendMessage(chat_id, "welcome to robin, please wait to be grouped")
print("sent message")
function1()
print("function1s working")
And here is the error just in case you need it
EDIT: Error as text
File "bot.py", line 133, in on_chat_message
function1()
NameError: name 'function1' is not defined
Traceback (most recent call last):
File "bot.py" line 223, in (module)
time.sleep(10)
The error occurs on line 133, presumably inside some function that is ultimately called from line 223 (if I'm interpreting your snippet correctly). Clearly, function1() is not defined at the time that your code reaches line 223.
If function1() appears before line 223 in the same file, it must be defined inside another function (or possibly a class) that limits the scope of its definition. Or possibly the definition is inside an if block that comes out False, or some such. Python function definitions are ordinary code, so it's possible to go past them without executing them.

Gui with button to open port scanner

I am making a GUI with tkinter that allows me to click a button that will run a port scan. I have a script for a port scan that functions correctly, I have managed to open the port scanner through the button on the GUI but then I receive an error that I otherwise don't receive when running the port scanner alone.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Steve\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "<string>", line 51, in Scan
NameError: name 'IP_Input' is not defined
My code:
class CallWrapper:
"""Internal class. Stores function to call when some user
defined Tcl function is called e.g. after an event occurred."""
def __init__(self, func, subst, widget):
"""Store FUNC, SUBST and WIDGET as members."""
self.func = func
self.subst = subst
self.widget = widget
def __call__(self, *args):
"""Apply first function SUBST to arguments, than FUNC."""
try:
if self.subst:
args = self.subst(*args)
return self.func(*args) # THIS IS THE ERROR #
except SystemExit:
raise
except:
self.widget._report_exception()
class XView:
"""Mix-in class for querying and changing the horizontal position
of a widget's window."""
def xview(self, *args):
"""Query and change the horizontal position of the view."""
res = self.tk.call(self._w, 'xview', *args)
THIS IS THE CODE FOLLOWING FOR THE LINE 51 ERROR
def Scan():
print ('Scan Called.') #Debugging
IP = str(IP_Input.get(0.0, tkinter.END)) #THIS IS ERROR LINE 51#
print ("IP #Debugging")
Start = int(PortS.get(0.0, tkinter.END))
End = int(PortE.get(0.0, tkinter.END))
TestSocket = socket.socket()
CurrentPort = Start
OpenPorts = 0
print ('Starting scan...')
HowFar = int(CurrentPort/End * 100)
ProgText = HowFar, r'%'
Label1.config(text=('Percentage Done:', ProgText))
The problem is with your exec statement. You're opening your other .py file named port_scanner.py and then calling exec(open("./port scanner.py)).
This just isn't going to work.
Why this doesn't work:
When you do exec(open("path to .py file").read()) exec is of course executing this code, but the problem is that the global variables in this file aren't within the scope.
So, to make this work (which I don't recommend) you'd have to use:
exec(open(path).read(), globals())
From the documentation
If the globals dictionary does not contain a value for the key builtins, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own builtins dictionary into globals before passing it to exec().
If you really want to call your file this way then you should just use os.system.
Alternative approach:
You really don't need to call your file this way. You now have two instances of Tk() running. If you need another window then a widget is provided for this purpose. It is the Toplevel widget. You can restructure your code to create a Toplevel instance containing the port scanner app on your button click. An example being, create your port scanner app with the Toplevel widget (in your other file if you wish) then import the "app" into your file and on the button click have it initialize the app.
Additional Notes:
You're calling a while loop and if this runs (for any noticeable amount of time) then this is going to block the GUI's main event loop and causing your GUI to "hang".
Your first guess should not be that a part of the widely tested and used python standard library is flawed. The problem is (99.9% of the time)
while True:
print("In your own code.")

Categories