How to get the get() func to work in tkinter? - python

def Main_Menu():
for widget in myframe_1.winfo_children():
widget.destroy()
PostIt_Count = len([name for name in os.listdir('C:/Users/Aatu/Documents/python/pythonleikit/tkinterstuff/PostItApp/PostIts')])
if PostIt_Count > 0:
for i in range(PostIt_Count):
PostIt_NamesList = [name for name in os.listdir('C:/Users/Aatu/Documents/python/pythonleikit/tkinterstuff/PostItApp/PostIts')]
PostIt_LabelName = 'PostItLabel' + str(i)
global selected_postit
selected_postit = tk.StringVar
PostIt_LabelName = ttk.Radiobutton(myframe_1, text=PostIt_NamesList[i], variable=selected_postit)
y = ([x for x in range(1, PostIt_Count +1)][i])- 0.4
y = str(y)[:1] + str(y)[2:]
yname = '.' + y
PostIt_LabelName.place(relx=.1, rely=yname)
def Read_PostIt():
for widget in myframe_3.winfo_children():
widget.destroy()
filepath = 'C:/Users/Aatu/Documents/python/pythonleikit/tkinterstuff/PostItApp/PostIts/'
postit = selected_postit.get()
f = filepath + postit
with open('{}'.format(f), 'r') as fi:
global text
text = fi.readlines()
fi.close()
text_label = Label(myframe_3, text='{}'.format(text))
text_label.place(relx=.01, rely=.01)
So when I run this I get TypeError: get() missing 1 required positional argument: 'self' , why does this happen and how can I fix this. I'm trying to do a Post-It app and I'd like to show the text of the post-it file. I'm calling the Main_Menu function when I start this app and the Read_PostIt function is called when I select a radiobutton of a post-it and click Read -button.
I don't know these kind of stuff very well and I would be veery glad if somebody helped.
Full error traceback:
PS C:\Users\Aatu\Documents\python\pythonleikit> & C:/Python39ni/python.exe c:/Users/Aatu/Documents/python/pythonleikit/tkinterstuff/PostItApp/post-its.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python39ni\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "c:\Users\Aatu\Documents\python\pythonleikit\tkinterstuff\PostItApp\post-its.py", line 73, in Read_PostIt
postit = selected_postit.get()
TypeError: get() missing 1 required positional argument: 'self'

Related

Tkinter callback() "TypeError: callback() takes 1 positional argument but 4 were given"

When I type into the entrybox, while i expect the console to print what i've typed the following error is raised:
Traceback (most recent call last):
File "/usr/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
TypeError: callback() takes 1 positional argument but 4 were given
class Editor:
def __init__(self,master):
self.master = master
self.edit_frame = tk.Frame(self.master)
self.elem_frame = tk.Frame(self.master)
self.naz = Nazioni()
paesi = [*self.naz.iso3]
print(paesi)
self.comb_paese = ttk.Combobox(self.edit_frame, value = paesi)
self.comb_paese.current(1)
self.kwordvar= tk.StringVar()
entry_keyword = tk.Entry(self.edit_frame, textvariable=self.kwordvar)
self.kwordvar.trace_add("write",self.callback)
writer = tk.Text(self.edit_frame)
writer.grid(row=0,column=0)
entry_keyword.grid(row=1, column=1)
self.comb_paese.grid(row=1, column = 0)
self.elem_frame.grid(row=0, column = 1)
self.edit_frame.grid(row=0,column=0)
def callback(self):
print(self.kwordvar)
The Editor class is being called with self.newWindow= tk.Toplevel(self.master) as argument, don't know if it has anything to do here but while searching for a solution I've read something about it.

Delete item from dictionary and Listbox

I have a program that puts the contents of a dictionary in a Tkinter Listbox, but I'm having trouble deleting it from the Listbox and the dictionary.
from tkinter import *
import ast
f = open("orders.txt", "r")
contents = f.read()
f.close()
things = ast.literal_eval(contents)
secondthing = [things, "test"]
root = Tk()
f = Frame(root).pack()
l = Listbox(root)
b = Button(root, text = "delete selection", command = lambda: delete(l))
b.pack()
l.pack()
for i, j in things.items():
oneitem = i + " " + j
l.insert(END, oneitem)
def delete(listbox):
global things
# Delete from Listbox
selection = l.curselection()
l.delete(selection[0])
# Delete from list that provided it
evaluater = l.get(selection[0])
value = eval(evaluater)
ind = things.index(value)
del(things[ind])
print(things)
root.mainloop()
When I try to delete something it gives me:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/__init__.py", line 1883, in __call__
return self.func(*args)
File "/Users/mimmo/black_market/aaa.py", line 12, in <lambda>
b = Button(root, text = "delete selection", command = lambda: delete(l))
File "/Users/mimmo/black_market/aaa.py", line 28, in delete
value = eval(evaluater)
File "<string>", line 1
ohhh ohhhhh
^
SyntaxError: unexpected EOF while parsing
Can someone help me because I can delete it from the Listbox, I just have an error when deleting it from the dictionary.
The contents of orders.txt:
{"ayyy" : "ayyyyyy", "ohhh" : "ohhhhh"}
First of all, I would recommend using json or pickle to store contents of the dictionary - it's the most common practice. I don't really understand what do you want to do so I wrote a function which deletes an element from listbox and things by it's index.
An error you are getting is caused by eval function which tries to intepret your listbox item as python code. Of course, it's getting syntax error.
# Deletes element from listbox and thigs by it's index
def delete(listbox, index: int):
global things
item = listbox.get(index)
key = item.split()[0]
del things[key]
listbox.delete(index)

TypeError: 'Entry' object is not callable

I am building an Python with Tkinter application, and one of the things it does is take input (from Entry boxes) and saves it. However, recently it has started creating this error code in multiple places:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Adam\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\Adam\Desktop\paintersinventory.py", line 2773, in grabpaintingname
saveedit()
File "C:\Users\Adam\Desktop\paintersinventory.py", line 2736, in saveedit
w = str(title[pnttoedit]) + " (" + str(copyat) + ")"
TypeError: 'Entry' object is not callable
Here is the related code, excluding the Tkinter box that pops up to ask for the information, which exists and correctly, after a button press sends the code to the grabpaintingname def:
painter = {}
title = {}
names = []
pnttoedit = ''
copyat = 1
def saveedit():
w = str(title[pnttoedit]) + " (" + str(copyat) + ")"
names.append(w)
v = painter[pnttoedit]
painter[w] = v
messagebox.showinfo("Painter's Inventory", "Copy of " + str(pnttoedit) + " created.")
print(str(pnttoedit))
def grabpaintingname():
global pnttoedit
pnttoedit = tvkare.get()
saveedit()
tvkare = StringVar(editers)
tvkare.set(names[0])
e2 = OptionMenu(mainframe, tvkare, *names)
e2.grid(row=3, column=1)
def change_dropdown(*args):
pnttoedit = tvkare.get()
Any help with how to solve this problem or information on why it might be occurring would be very much appreciated. Thank you in advance!
Just wanted to mark that it was solved by Bryan Oakley.
I had variables called str accidentally.

Python - global name is not defined when calling function from class __init__ method

I am new to Python and working on a class for storing meaningful data pieces about books. I have started as follows:
class BookDisplay:
def __init__(self, _name, _isbn, _price, _picture, _link):
self.name = _name
self.isbn = _isbn
self.price = _price
self.picture = _picture
self.link = _link
self.xmlString = MakeXMLString(_name, _isbn, _price, _picture, _link)
name = ""
isbn = ""
price = 0.0
picture = "" #a URL
link = ""
xmlString = ""
I thought this __init__ method would just be able to call MakeXMLString, which I defined in the same file (bookdisplay.py), right below the BookDisplay class:
def MakeXMLString(_name, _isbn, _price, _picture, _link): #python multi-line syntax
xmlString = "<name>" + _name + "</name>" \
+ "<isbn>" + _isbn + "</isbn>" \
+ "<price>" + str(_price) + "</price>" \
+ "<picture>" + _picture + "</picture>" \
+ "<link>" + _link + "</link>"
return xmlString
Originally, I actually had MakeXMLString as a method within the class, like this:
def MakeXMLString(self):
self.xmlString = "<name>" + self.name + "</name>" \
+ "<isbn>" + self.isbn + "</isbn>" \
+ "<price>" + str(self.price) + "</price>" \
+ "<picture>" + self.picture + "</picture>" \
+ "<link>" + self.link + "</link>"
In that case, __init__ contained this call:
self.xmlString = self.MakeXMLString()
In both cases, when trying to instantiate BookDisplay from another file:
from bookdisplay import BookDisplay
...
...
thumbnails = []
...
thumbnails.append(BookDisplay(titleField, "-1", float(priceField), imgField, linkField))
...I get the following global name error (this traceback in particular for the not-within-class function):
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "search.py", line 30, in ebaySearch
handleDocument(doc)
File "search.py", line 59, in handleDocument
handleItems(items, outputFile)
File "search.py", line 102, in handleItems
thumbnails.append(BookDisplay(titleField, "-1", float(priceField), imgField, linkField))
File "bookdisplay.py", line 15, in __init__
self.xmlString = MakeXMLString(_name, _isbn, _price, _picture, _link)
NameError: global name 'MakeXMLString' is not defined
What am I missing here? From what I can tell, MakeXMLString is perfectly accessible to the class.
when you defined MakeXMLString as a method, it is not returning anything so
self.xmlString = self.MakeXMLString()
will overwrite self.xmlString and make it point to the method itself.
With the way you have it defined now, MakeXMLString is not accessible from the other file, so you have to manually import it as well by doing:
from bookdisplay import BookDisplay, MakeXMLString
EDIT:
upon rereading, you aren't calling MakeXMLString from the other file, so the error is in bookDisplay.py; make sure
def MakeXMLString()
is on the same indent level as the class definition, otherwise it'll be interpreted as a method.

Class Variable Retrieval in Python

This is a GUI I’ve been writing for a script I already have working. What I’m struggling with here is retrieving the information in the textboxes.
Under the definition generate I am able to pop a name off of listx but I am unable to grab the local variable entry from any of the instances of the new_title_box class.
from Tkinter import *
import ttk
boxvar=""
folder=""
listx=[]
count = 1
myrow = 1
class new_title_box:
def __init__(self,name):
global myrow, count, listx
self.entry = StringVar()
self.name = name
self.name = ttk.Entry(mainframe,width=45,textvariable=self.entry)
self.name.grid(column=1,row=myrow+1,sticky=(N,W))
listx.append(name)
print(listx) ## For debugging to insure that it is working correctly, if it gives output it, this part works
myrow = myrow + 1
count=count+1
def make_new(*args):
new_title_box('box'+str(count))
def generate(*args):
global listx, boxvar
while len(listx) > 0:
boxvar=listx.pop(0)
print(boxvar) ## For debugging to insure that it is working correctly, if it gives output it, this part works
folder = boxvar.entry.get() ## Not working here
print(folder) ## For debugging to insure that it is working correctly, if it gives output it, this part works
root = Tk()
root.title("File Maker")
mainframe = ttk.Frame(root, padding = "50 50 50 50")
mainframe.grid(column = 0,row = 0,sticky = (N, W, E, S))
mainframe.columnconfigure(0,weight=1)
mainframe.columnconfigure(0,weight=1)
add_entry = ttk.Button(mainframe,width=20, text = "add entry", command=make_new)
add_entry.grid(column=2,row=2,sticky=(N,W))
add_entry = ttk.Button(mainframe,width=20, text = "make files", command=generate)
add_entry.grid(column=2,row=3,sticky=(N,W))
root.mainloop()
Here's the traceback I'm getting:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter_init_.py", line 1442, in call
return self.func(*args)
File "C:\python\SampAqTkinter.py", line 28, in generate
folder = boxvar.entry ## Not working here
AttributeError: 'str' object has no attribute 'entry'
There are two things that need to be changed to fix the problem you describe:
In the new_title_box.__init__() method change: listx.append(name) to listx.append(self.name)
In the generate() function, change: folder = boxvar.entry.get() to folder = boxvar.get().
You are appending a string to listx, use self.name instead of the local string name

Categories

Resources