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

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.

Related

curselection on treeview tkinter

I'm trying to extract the data of what row is selected on a treeview in tk.
So far I've tried the following:
def select_item(event):
global selected_item
index = data.curselection()[0]
selected_items = data.get(index)
print(selected_items)
#configure scrollbar
my_tree.bind('<<TreeviewSelect>>', select_item)
I was following a tutorial of some guy doing it, and my data layout is the exact same as his, as can be seen:
data = [('0','John', 'Smith','1','2','3'),('1','Ayoung', 'Smith','2','3','6'),('2','Enshean', 'Smith','6','1','4'),
('3','Emma', 'Smieth','1','4','5'),('4','Isabel', 'Smith','6','1','4')]
When I try my running my code and selecting an item on the treeview I get the following 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/johnminton/Documents/Python/Python database internal/deletestudent.py", line 35, in select_item
index = data.curselection()[0]
AttributeError: 'list' object has no attribute 'curselection'
I used the following, and it does its job.
def select_item(event):
rowid=my_tree.identify_row(event.y)
item=my_tree.item(my_tree.focus())
print(item['values'])
my_tree.bind('<ButtonRelease-1>', select_item)
The error is telling you that data is a list, not a treeview widget. You must call curselection() on a treeview object. Well, except for the case that even the Treeview widget doesn't have that method. To get the currently selected items in Treeview you use selection., In your case it should be one of the following:
event.widget.selection()
... or the following, assuming that my_tree is a global variable:
my_tree.selection()

Calling an object method using a function

I am playing around tkinter, and I was wondering if I had declared a method within an object, can I call it using the 'protocol' method of tkinter? or any function to be exact ie.
class Notepad():
...
...
def exit_func():
#Messagebox command warning 'You are exiting'
root = tk.Tk()
notepad = Notepad(root)
root.geometry("800x500")
root.mainloop()
#Problem is here
root.protocol("WM_DELETE_WINDOW", app.exit_func())
I tried this with my program, where my 'exit_func' had a 'get' function from tkinter and i got this error:
Traceback (most recent call last):
File "Notepad_with_console.py", line 204, in <module>
root.protocol("WM_DELETE_WINDOW", notepad.exit_file())
File "Notepad_with_console.py", line 175, in exit_file
if self.text.get(1.0,tk.END) != '' and self.current_file_dir == '':
File "C:\Anaconda\lib\tkinter\__init__.py", line 3246, in get
return self.tk.call(self._w, 'get', index1, index2)
_tkinter.TclError: invalid command name ".!text"
Is there a reason for this? Thanks!
root.protocol requires a reference to a function. Instead, you're immediately calling a function and then passing in the result.
Consider this code:
root.protocol("WM_DELETE_WINDOW", app.exit_func())
That code is functionally identical to this:
result = app.exit_func()
root.protocol("WM_DELETE_WINDOW", result)
Instead, you need to pass in a reference to the function:
root.protocol("WM_DELETE_WINDOW", app.exit_func)

Python tkinter trace error

I'm trying to write a GUI for my code. My plan is to use tkinter's StringVar, DoubleVar, etc. to monitor my input in real time. So I found out the DoubleVar.trace('w', callback) function. However, every time I make the change I get an exception:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Anaconda2\lib\lib-tk\Tkinter.py", line 1542, in __call__
return self.func(*args)
TypeError: 'NoneType' object is not callable
I have no idea what's going wrong. I'm using python 2.7
My code is as follows:
from Tkinter import *
class test(Frame):
def __init__(self,master):
Frame.__init__(self,master=None)
self.main_frame = Frame(master);
self.main_frame.pack()
self.testvar = DoubleVar()
self.slider_testvar = Scale(self.main_frame,variable = self.testvar,from_ = 0.2, to = 900, resolution = 0.1, orient=HORIZONTAL,length = 300)
self.slider_testvar.grid(row = 0, column = 0, columnspan = 5)
self.testvar.trace('w',self.testfun())
def testfun(self):
print(self.testvar.get())
root = Tk()
root.geometry("1024x768")
app = test(master = root)
root.mainloop()
Consider this line of code:
self.testvar.trace('w',self.testfun())
This is exactly the same as this:
result = self.testfun()
self.testvar.trace('w', result)
Since the function returns None, the trace is going to try to call None, and thus you get 'NoneType' object is not callable
The trace method requires a callable. That is, a reference to a function. You need to change that line to be the following (notice the missing () at the end):
self.testvar.trace('w',self.testfun)
Also, you need to modify testfun to take arguments that are automatically passed by the tracing mechanism. For more information see What are the arguments to Tkinter variable trace method callbacks?

How to set Entry.get as an argument of a command function with lambda in python Tkinter

I have an application that has a entry field and a button:
from subprocess import *
from Tkinter import *
def remoteFunc(hostname):
command = 'mstsc -v {}'.format(hostname)
runCommand = call(command, shell = True)
return
app = Tk()
app.title('My App')
app.geometry('200x50+200+50')
remoteEntry = Entry(app)
remoteEntry.grid()
remoteCommand = lambda x: remoteFunc(remoteEntry.get()) #First Option
remoteCommand = lambda: remoteFunc(remoteEntry.get()) #Second Option
remoteButton = Button(app, text = 'Remote', command = remoteCommand)
remoteButton.grid()
app.bind('<Return>', remoteCommand)
app.mainloop()
and I want that when I insert an ip/computer name to the entry field it will sent it as a parameter to the command of the button, so when I press Return or pressing the button it will remote the computer with that name/ip.
When i execute this code with the first option (look at the code) it works only I press the Return key, and if I press the button this is the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1532, in __call__
return self.func(*args)
TypeError: <lambda>() takes exactly 1 argument (0 given)
If I try the second option of remoteCommand only if I try to press the button It work but I if press the Return key i get this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1532, in __call__
return self.func(*args)
TypeError: <lambda>() takes no arguments (1 given)
The only difference between the two is if lambda gets an argument or not.
The best solution in my opinion is to not use lambda. IMO, lambda should be avoided unless it really is the best solution to a problem, such as when a closure needs to be created.
Since you want the same function to be called from a binding on the return key, and from the click of a button, write a function that optionally accepts an event, and then simply ignores it:
For example:
def runRemoteFunc(event=None):
hostname = remoteEntry.get()
remoteFunc(hostname)
...
remoteButton = Button(..., command = remoteFunc)
...
app.bind('<Return>', remoteCommand)
Commands do not get arguments. Event handlers get an event as an argument. To have a function serve as both, use a default argument.
def remote(event=None):
remoteFunc(remoteEntry.get())

global name 'display' is not found

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)

Categories