How to resolve this error in Python? - python

I know this will be marked as a duplicate post as there were some questions about this error. I've gone through those, but got no idea how to resolve it. Please help me. Here is the error message.
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__
return self.func(*args)
File "iptrace.py", line 21, in mbt
tkMessageBox.showinfo(tget, tget+" lives in "+jd["city"]+", "+jd["region"]+" "+jd["country"])
TypeError: cannot concatenate 'str' and 'NoneType' objects
Here is the code:
from Tkinter import *
import tkMessageBox
import json
import urllib
import sys
def wmi():
uip = urllib.urlopen("http://www.networksecuritytoolkit.org/nst/tools/ip.php").read()
tkMessageBox.showinfo("Whats my IP", "Your IP is "+uip)
def mbt():
global ew1
tget = ew1.get().strip()
jd = json.load(urllib.urlopen("http://ipinfo.io/"+tget+"/geo"))
if tget == "":
tkMessageBox.showerror(tget, "Type a IP Please")
else:
tkMessageBox.showinfo(tget, tget+" lives in "+jd["city"]+", "+jd["region"]+" "+jd["country"])
if __name__ == "__main__":
root = Tk()
root.title("-|IP2Location|-")
textFrame = Frame(root)
entryLabel = Label(textFrame)
entryLabel["text"] = "IP :"
entryLabel.pack(side=LEFT)
ew1 = Entry(textFrame)
ew1["width"] = 24
ew1.pack(side=LEFT)
textFrame.pack()
bmi = Button(root, text="Whats my IP", command=wmi)
bmi.pack()
bs = Button(root, text="Submit", command=mbt)
bs.pack()
def enterPress(event):
mbt()
root.bind("<Return>", enterPress)
def enterPress(event):
exit()
sys.exit(0)
root.bind("<Escape>", enterPress)
root.mainloop()

The error, as stated in the Traceback is located in:
else:
tkMessageBox.showinfo(tget, tget+" lives in \
"+jd["city"]+", "+jd["region"]+" "+jd["country"])
So what's causing the problem is you're using the + sign for two different types, one being a string and the other NoneType (i.e. has no value).
So what you'll need to do is change the predefined variables to strings using str(var) that you're trying to concatenate within that statement. Only then it'll run without issue.

Related

python3 with tkinter: call widget from a function

I'm having a problem with this code:
from tkinter import *
class app:
def create(arrSettings):
proot = Toplevel()
proot.title("Settings")
m = Frame(proot).pack() #Some Frames so I can arrange them how I'd like to
mcan = Canvas(proot)
mcan.pack(fill="both", side="left")
x = Frame(proot).pack()
xcan = Canvas(proot)
xcan.pack(fill="both", expand="yes", side="left")
win_0 = Frame(xcan)
lbl_0 = Label(win_0, text="Option0").pack()
txt_0 = Text(win_0).pack()
win_0.pack()
win_1 = Frame(xcan)
lbl_1 = Label(win_1, text="Option1").pack()
txt_1 = Text(win_1).pack()
win_1.pack()
btn_menu0 = Button(mcan, text="Menu0", command=app.func_btn_menu0).pack()
btn_menu1 = Button(mcan, text="Menu1", command=app.func_btn_menu1).pack()
def func_btn_menu0():
lbl_0.config(text="foo") # <-- Problem
txt_0.insert("end", "bar") # <-- Problem
def func_btn_menu1():
pass
(I left the code for the design(bg, border, ...) out)
This is another window which will be started by the main one.
It shows some buttons on the left and some labels and textboxes on the right.
Whenever a button on the left has been pushed the text of the labels should be changed.
That's the problem: When I push a button I get this error and the text won't be changed:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
return self.func(*args)
File "/[...]/program.py", line 27, in colormain
lbl_0.config(text="Background")
NameError: name 'lbl_0' is not defined
I don't really understand why this gives me an error so I'd like to ask you.
This code is being started from the main window with the code:
program.app.create(arrSettings) #arrSettings is an array in which some colors for the design are
Thanks in advance.
Do not declare and pack in the same line
Return of this peice of code is None
Label(win_0, text="Option0").pack()
whereas, this returns an object of Label class
Label(win_0, text="Option0")
so use:-
lbl_0 = Label(win_0, text="Option0")
lbl_0.pack()
instead of
lbl_0 = Label(win_0, text="Option0").pack()
Also use self object as argument to functions. Check that the variables are in scope wherever you are using it.
This should help you get through this error...

Seeking Help: python2.7: working on this function; want to get input from "def proceed3()" to "def openChrome()"

How do i pass my website_name which is a URL, https://www.google.com/ for instance; from "def proceed3()" to "def openChrome()" ? Any Suggestions?
from Tkinter import *
def proceed3():
popup = Toplevel()
popup.geometry("350x175+350+180")
popup.resizable(width=False, height=False)
instruction = Label(popup, text="Enter the URL and pressGO!").pack()
website_name = Entry(popup, width=50).pack(pady=5)
goButton = Button(popup, text="GO!", command=openChrome)
goButton.pack(pady=5)
def openChrome():
openWebsite = website_name.get()
os.system(r"start chrome " + openWebsite)
windows = Tk()
windows.geometry("200x200+375+280")
windows.resizable(width=False, height=False)
submitButton = Button(windows, text='OpenChrome', command=proceed3)
submitButton.pack(pady=5)
windows.mainloop()
TRACEBACK ERROR:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1542, in __call__
return self.func(*args)
File "E:/educational_data/PyCharmProjects/web_grabber/starflow_grabber.py",
line 15, in openChrome
openWebsite = website_name.get()
NameError: global name 'website_name' is not defined
Add
return website_name to the end of your proceed3() function
Add an argument website_name to your OpenChrome() function.
def proceed3():
popup = Toplevel()
popup.geometry("350x175+350+180")
popup.resizable(width=False, height=False)
instruction = Label(popup, text="Enter the URL and pressGO!").pack()
website_name = Entry(popup, width=50).pack(pady=5)
goButton = Button(popup, text="GO!", command=openChrome)
goButton.pack(pady=5)
return website_name
def openChrome(website_name):
os.system(r"start chrome " + website_name)
I would suggest reading this tutorial regarding how to work with functions in python, as this will be fundamental to furthering your programming efforts.

Python, 'tkinter' has no attribute 'get'

I'm trying to print the value xf_in which is entered in the GUI.
However, I get the following error message when i press the run button:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\My_Name\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/My_Name/Python Scripts/test/gui.py", line 6, in EP
xf_In = tk.get(e_xf)
AttributeError: module 'tkinter' has no attribute 'get'
I've tried to find the source of the error online but to no avail.
Thanks in advance for any help
My code is as follows:
import tkinter as tk
from PIL import ImageTk as imtk
from PIL import Image as im
def EP(): # Enter inputs from values typed in
xf_In = tk.get(e_xf)
print(xf_In)
root = tk.Tk()
l_xf = tk.Label(root, text="xA of Feed").grid(row=0)
e_xf = tk.Entry(root).grid(row=0, column=1)
run = tk.Button(root, text="Run", command=EP).grid(row=8, column=0, columnspan = 2)
img = imtk.PhotoImage(im.open("x.png"))
panel = tk.Label(root, image = img).grid(row = 0, column = 2, rowspan = 7)
root.mainloop()
As the error message indicates, the tk module does not have a function named get. It might have plenty of classes whose instances have a get method, but you can't access them the way you're doing.
If you're trying to get the contents of the Entry, you should assign it to a name, and call get on that instead:
def EP(): # Enter inputs from values typed in
xf_In = e_xf.get(e_xf)
print(xf_In)
#...
e_xf = tk.Entry(root)
e_xf.grid(row=0, column=1)
Note that this assignment is different from doing e_xf = tk.Entry(root).grid(row=0, column=1). If you do that, then e_xf will be bound to the return value of grid, rather than the Entry instance. grid returns None, so trying to call get on that would only give you an AttributeError. Related reading: Why do my Tkinter widgets get stored as None?

AttributeError: 'NoneType' object has no attribute 'grid_remove'

I have only done a little work with Tkinter and I enjoy using it but as with any type programing it takes time to learn. I am trying to create a simple To do list that will eventually be saved on a file. But i can't get the button in line 17 to be removed and the on the next line be replace in a different position.
from tkinter import *
import time
root = Tk()
root.geometry("300x300")
root.title("Programs")
global TDrow
TDrow = 2
def tdTaskAdd():
global TDrow
global tdEnter
TDrow = int(TDrow+1)
s = tdEntry.get()
label = Label(ToDoFrame,text=s).grid(row=TDrow,column=1)
tdEntry.grid(row=TDrow+1,column=1)
tdEnter.grid_remove()
tdEnter = Button(ToDoFrame,text="AddTask",command=tdTaskAdd).grid(row=TDrow+2,column=1)
ToDoFrame = Frame()
ToDoFrame.place(x=0,y=10)
tdTitle = Label(ToDoFrame,text="To Do List:").grid(row=TDrow-1,column=1)
tdEntry= Entry(ToDoFrame)
tdEntry.grid(row=TDrow+1,column=1)
tdEntry.insert(0, "Enter a new task")
global tdEnter
tdEnter = Button(ToDoFrame,text="Add Task",command=tdTaskAdd).grid(row=TDrow+2,column=1)
mainloop()
I keep getting an error when running this saying that:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Users\Eddy\Desktop\pythonStartup.py", line 17, in tdTaskAdd
tdEnter.grid_remove()
AttributeError: 'NoneType' object has no attribute 'grid_remove'
The problem is this line:
tdEnter = Button(ToDoFrame,text="Add Task",command=tdTaskAdd).grid(row=TDrow+2,column=1)
This way, tdEnter is not the Button, but the return value of grid, i.e. None.
Try this instead:
tdEnter = Button(ToDoFrame,text="Add Task",command=tdTaskAdd)
tdEnter.grid(row=TDrow+2,column=1)
Same for label and when you create a new button in your tdAddTask function.
BTW, no need to add a new button each time, just call it's grid method to repositon it.

Tkinter Trace and ValueError: invalid literal for int() with base 10: ''

I'm new to Python/programming, so please be gentle! I've been fairly good at figuring stuff out for myself (or finding answers here!) so far, but i've been struggling with this for a while now..
Using Tkinter, I want a label to print the sum of two entry fields, updating automatically after each entry input. This is where I've got to:
from Tkinter import *
import ttk
root = Tk()
first_var = IntVar()
second_var = IntVar()
total_var = IntVar()
para = [0, 0]
def totalupdate(*args):
global para
para[0] = first_var.get()
para[1] = second_var.get()
newtotal = sum(para)
total_var.set(newtotal)
first_var.trace('w', totalupdate)
second_var.trace('w', totalupdate)
first = ttk.Entry(root, textvariable=first_var)
second = ttk.Entry(root, textvariable=second_var)
total = ttk.Label(root, textvariable=total_var)
first.grid()
second.grid()
total.grid()
root.mainloop()
So, this seems to work fine within the Tk window, but it throws up
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/T‌​kinter.py", line 1410, in __call__
File "para.py", line 15, in totalupdate
para[1] = second_var.get()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/T‌​kinter.py", line 283, in get
ValueError: invalid literal for int() with base 10: ''
in the terminal window any time I use .get() within a trace callback function. I've tried multiple ways of getting around this to no avail. I'm sure there's a pretty simple solution, and it doesn't seem to affect the program but its bugging me! Any help much appreciated, as well as any comments concerning a better way to achieve what I'm trying to do. Many thanks!
Whenever your first variable changes, the trace is triggered, but the second value is still empty. An empty string is not an integer, and the exception is thrown.
In this case, I'd catch that exception and simply return, until both variables hold proper integers:
def totalupdate(*args):
global para
try:
para[0] = first_var.get()
para[1] = second_var.get()
except ValueError:
# one or both values are not integers
return
newtotal = sum(para)
total_var.set(newtotal)

Categories