Errors when trying to clear Tkinter Entry Widget - python

I am working on a project that will eventually simulate a filter for Twitter posts. I am trying to make a page in Tkinter that will allow the user to enter a Twitter account, and press a button that will add the string to a list and clear the entry field (have yet to code the append function). Code is as follows:
def Add():
F.title('Twitter Filter: Add to Filter')
def h_delete():
Entry.delete(h,first=0,last=END) # should clear entry, instead returns NoneType error
for widget in F.winfo_children():
widget.destroy() # clears widgets of previous window
global a1
a1=tk.StringVar() # declares a variable that will be used to append a list with the text in the Entry
h=tk.Entry(F,textvariable=a1).grid(row=1,column=1) # creates the entry I want cleared
EntryButton=tk.Button(F,text='Add this account',command=h_delete).grid(row=2,column=1) # initiates the entry clearing function
BackButton=tk.Button(F,text='Back to Home',command=Home).grid(row=3,column=1) # returns to home screen
However, when I run the code, I receive a NoneType error, as follows:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1550, in __call__
return self.func(*args)
File "/Users/skor8427/Desktop/Twitter Filter/TwitterFilter.py", line 22, in h_delete
Entry.delete(h,first=0,last=END) # should clear entry, instead returns NoneType error
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 2519, in delete
self.tk.call(self._w, 'delete', first, last)
AttributeError: 'NoneType' object has no attribute 'tk'
I have read various help sections and nothing is working. Anyone have a solution?

h = tk.Entry(F, textvariable=a1)
h.grid(row=1, column=1)
You have to grid h in other line else it will become NoneType
Try this snippet of code instead of
h = tk.Entry(F, textvariable=a1).grid(row=1, column=1)

Related

Getting "TypeError: insertstop() takes 0 positional arguments but 1 was given" when there are no arguments in my function calls

I'm very new to Python and I'm trying to put my first application together that takes in trip information and inserts it into a text box for export out to a document. It's gone pretty good until today when I tried to implement multiple ways of inserting text from an entrybox into a text block with tkinter.
I have an entry widget that inserts text into a text widget when a button is pressed. That's simple enough but I wanted to make it to where you could simply hit the enter key to do the same thing.
When I implement this function I get the error:
"Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Spyder\pkgs\tkinter_init_.py", line 1892, in __ call __
return self.func(*args)
TypeError: insertstop() takes 0 positional arguments but 1 was given"
I've looked the error up and it seems like it would pop up if I put in arguments in my function call but I don't have any arguments in any of my function calls. Also it seems like maybe this error is related to a class or something? I haven't learned about classes yet and only have a basic idea of what they are. Do I need a class to do this?
Coincidentally I also added the argument(self) in my function and that made pressing enter work but it made my insert stop button quit working.
I'm sure I've missed something very basic but I just can't figure out what.
Thanks for any help!
import time
import os
import sys
from tkinter import *
# Creates the Tkinter form named "screen"
screen = Tk()
screen.geometry("550x645")
screen.title("Test")
# Initialize frames
menuframe = Frame(screen,
height=60,width=600,bg="gray",pady=5)
inputframe = Frame(screen,
height=300,width=600,pady=5)
outputframe = Frame(screen,
height=290,width=600,pady=5)
# Packs the frames so they will display
menuframe.pack()
inputframe.pack()
outputframe.pack()
#==STOPBOX==#
stopbox=Text(inputframe,yscrollcommand=1,height= 10,width=20,
padx=3,pady=3,relief=GROOVE,bg="gray79")
stopbox.place(x=345, y=90)
def insertstop():
global stop_vanconv
stop_vanconv=(stop_entry.get())
stopbox.insert(END, stop_vanconv + "\n")
stop_entry.delete("0","end")
stoplist_label = Label(inputframe,
text="Type stop locations and press" + '\n' +
"the Add Stop button to insert a new stop.")
stoplist_label.place(x=100, y=150)
stop_entry = Entry(inputframe,
textvariable = " ")
stop_entry.place(x=150, y=190)
addstopbutton = Button(inputframe,text="Add Stop",padx=20,pady=0,
activebackground="darkslategray4",command=insertstop)
addstopbutton.place(x=160, y=220)
stop_entry.bind('<Return>',insertstop)
screen.mainloop()

how to take values from user 2nd time on tkinter entry widget

Here I am writing a code to give a different "mode" option to the user, after pressing the mode button my entry widget pops up and takes two values from the user for further work.
once the user presses the "enter" button my widget will be destroyed.
Here is my code ,it successfully takes values once from the user but when the user gives values 2nd time it shows error.
import tkinter as tk
import time
root=tk.Tk()
root.geometry("600x600")
root.title("User Interface Monitor")
rpm=tk.StringVar()
tim=tk.StringVar()
def enter():
global rpm,tim
root.rpmLabel=tk.Label(root,text="enter rpm value:")
root.rpmLabel.grid(row=0)
root.timeLabel=tk.Label(root,text="enter time in sec")
root.timeLabel.grid(row=1)
root.e1 = tk.Entry(root, textvariable=rpm)
root.e1.grid(row=0, column=1)
root.e1.delete(0,"end")
root.e2 = tk.Entry(root, textvariable=tim)
root.e2.grid(row=1, column=1)
root.e2.delete(0, "end")
#rpm=rpm.get()
#tim=tim.get()
#return rpm,tim
def gett():
global rpm, tim
rpm = rpm.get()
tim = tim.get()
print(rpm)
print(tim)
root.rpmLabel.destroy()
root.e1.destroy()
root.timeLabel.destroy()
root.e2.destroy()
#e1.pack()
#e2.pack()
root.Button1=tk.Button(root,text="MODE1",command=enter)
root.Button1.pack()
root.Button1.place(x=200,y=200)
root.Button2=tk.Button(root,text="Enter",command=gett)#root.Button2.pack()
root.Button2.place(x=260,y=200)
root.mainloop()
Here is my error
C:/Users/RAM/PycharmProjects/timing/rpm.py
23
2
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\RAM\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:/Users/RAM/PycharmProjects/timing/rpm.py", line 25, in gett
rpm = rpm.get()
AttributeError: 'str' object has no attribute 'get'
Process finished with exit code 0
I am new to Python, I couldn't find the solution for this error as tried with "delete" and "reset".
The problem is that rpm starts out as a StringVar and then you reset it to be a string in this line of code:
rpm = rpm.get()
Once that line of code runs, rpm is no longer a StringVar. A simple solution is to use a different name when fetching the value:
rpm_value = rpm.get()
Here, after carefully observing the error messages...
I changed my code line as Bryan suggested
rpm = rpm.get()
tim = tim.get()
to
rpm_value = rpm.get()
tim_value = tim.get()
then it works exactly as I want.
here is my output:
C:/Users/RAM/PycharmProjects/timing/rpm.py
rpm is : 740
time is : 12
want to test again?
enter values again
rpm is : 920
time is : 18
want to test again?
enter values again
Process finished with exit code 0

Tkinter/Python - Simple Login Application NoneType Error [duplicate]

This question already has answers here:
Tkinter: AttributeError: NoneType object has no attribute <attribute name>
(4 answers)
Closed 5 years ago.
I am trying to develop a simple login desktop app with tkinter lib. My code is working but when I'm trying to login with correct username and password it's giving the NoneType error. I am writing my codes on Pycharm. Here is my code:
from tkinter import *
window=Tk()
rootname = "Casca"
rootpasswd = "12345"
def loginfunc():
passwd=plogin.get()
name=ulogin.get()
if name==rootname and passwd==rootpasswd:
print("Successfull Login")
else:
print("Unauthorized User")
username=Label(text="Username:",font="Consolas,20").grid(row=0,column=0)
ulogin=Entry(font="Consolas,20",width=8).grid(row=0,column=1)
passwd=Label(text="Password:",font="Consolas,20").grid(row=1,column=0)
plogin=Entry(font="Consolas,20",width=8,show="*").grid(row=1,column=1)
sremember=Checkbutton(text="I forgot my password",font="Consolas,20").grid(row=2,column=0,columnspan=2)
login=Button(text="Login",font="Consolas,20",command=loginfunc).grid(row=3,column=0)
window=mainloop()
And here is the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "BLABLABLA", line 1699, in __call__
return self.func(*args)
File "BLABLABLA", line 9, in loginfunc
passwd=plogin.get()
AttributeError: 'NoneType' object has no attribute 'get'
Entry() returns the instance of the tkinter entry widget
Entry().grid() returns NoneType.
Change your code as shown below
from tkinter import *
window=Tk()
rootname = "Casca"
rootpasswd = "12345"
def loginfunc():
passwd=plogin.get()
name=ulogin.get()
if name==rootname and passwd==rootpasswd:
print("Successfull Login")
else:
print("Unauthorized User")
username=Label(text="Username:",font="Consolas,20").grid(row=0,column=0)
ulogin=Entry(font="Consolas,20",width=8)
ulogin.grid(row=0,column=1)
passwd=Label(text="Password:",font="Consolas,20").grid(row=1,column=0)
plogin=Entry(font="Consolas,20",width=8,show="*")
plogin.grid(row=1,column=1)
sremember=Checkbutton(text="I forgot my password",font="Consolas,20").grid(row=2,column=0,columnspan=2)
login=Button(text="Login",font="Consolas,20",command=loginfunc).grid(row=3,column=0)
window=mainloop()
You will have to do the same thing with the checkbox to get it's value.
You should also consider IntVar and StringVar variables to store the contents of these widgets.
When you do plogin = Entry(...).grid(...) you replace plogin with the result of .grid(), which is None. To fix this, you could do:
plogin = Entry(...)
plogin.grid(...)
and similar for all the other widgets.

How can the variable be used by other functions in TkfileDialog?

I intended to write a GUI to import URLs data then process these data,
so I had 2 buttons. Below is my code.
from Tkinter import *
root=Tk()
root.title('Videos Episodes')
root.geometry('500x300')
def OpenFile(): # import URLs data from local machine
paths=tkFileDialog.askopenfilename()
return paths
def read_files(paths): #read data from the directory from OpenFile
with open(paths) as myfile:
return data
Button(root,text='Input',command=OpenFile).pack()
Button(root,text='Process',command=read_files).pack()
root.mainloop()
My problem is that when 'Process' button clicked, error happened:
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args) TypeError: read_files() takes exactly 1 argument (0 given)
How can I fix the bug?
If you want to pass an argument (you didn't specify what), use a lambda:
Button(root,text='Process',command=lambda: read_files('whatever')).pack()
Perhaps, this is what you wanted to do (?):
Button(root,text='Process',command=lambda: read_files(OpenFile())).pack()
or alternatively, you meant to store the result of OpenFile (from clicking the other button) in a global variable, and pass that as argument of read_files...?

Why photoimages don't exist?

I will show a reduced portion of the code that gives me a problem.
_tkinter.TclError: image "pyimageN" doesn't exist - where N stays for 1, 2, 3, etc...
There is a first class that shows a menu using an image in the background.
class MenuWindow(): #in this class we show the main part of the program
def __init__(self):
self.Menu=Tk()
self.MCanvas=Canvas(self.Menu)
self.MCanvas.bind("<ButtonPress-1>",self.MenuClick)
#unuseful lines that configure the window and the canvas#
self.Background=PhotoImage(height=600,width=700)#a simple tkinter.PhotoImage object
#other unuseful lines that draw the photoimage ( without reading any file, with the method put())#
self.MCanvas.create_image((x,y),image=self.Background,state="normal")
#unuseful lines that continue the drawing of the canvas#
And a second class that shows another window, using another image in the background. This class is launched by the first class via click binding of the function self.MenuClick.
class EditorWindow(): #in this class we show the main part of the program
def __init__(self):
self.Eenu=Tk()
self.ECanvas=Canvas(self.Eenu)
#unuseful lines that configure the window and the canvas#
self.Background=PhotoImage(height=600,width=700)
#other unuseful lines that draw the photoimage ( without reading any file , with the method put() )#
self.ECanvas.create_image((x,y),image=self.Background,state="normal")#in this line i get the error
#unuseful lines that continue the drawing of the canvas#
The complere traceback is the following:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 1399, in __call__
return self.func(*args)
File "/Users/albertoperrella/Desktop/slay.py", line 70, in MenuClick
EditorWindow(self)
File "/Users/albertoperrella/Desktop/slay.py", line 85, in __init__
self.ECanvas.create_image((3,3),image=self.Background,state="normal",anchor="nw")
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 2140, in create_image
return self._create('image', args, kw)
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/tkinter/__init__.py", line 2131, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: image "pyimage2" doesn't exist
The two classes are made in a similar way, so I don't know why I get the error with the second one. I am sure that it isn't a writing error e.g.(conttruct instead of construct) and that the images I am using actually exist.
So I think that:
I am making some concept mistakes,
or it is a bug (or subtle behaviour of Tkinter) in python.
I solved myself the problem :
The second class I defined was the problem cause it used another root window, alias Tk(). An equivalent to the normal Tk() window is the Toplevel() that is the same as a root but hasn't its own interpreter context.
Shortly, to solve the problem I had to change the first line of the init() method of the EditorWindow class from
self.Eenu=Tk()
to
self.Eenu=Toplevel()
Just change the master argument in ImageTk.PhotoImage() to the respective window, like this:
ImageTk.PhotoImage(Image.open("photo.png"), master=self.window)
And everything will be alright.

Categories

Resources