Error with tkinter Create and Move - python

Im having a bit of a problem with my project. My game is running fine but we're not allowed to have errors in our shell. I have created a game where balloons come flying at you and you have to pop them with an arrow controlled by the keyboard.
My tkinter is throwing out a TclError with Invalid Command Name when I use move and create.
Here is my coding:
#Add balloons to the canvas and make them fly
import random
balloon_id = list()
balloon_radius = list()
balloon_speed = list()
MIN_BALLOON_RADIUS = 10
MAX_BALLOON_RADIUS = 30
MAX_BALLOON_SPEED = 10
GAP = 100
def create_balloon():
x = WIDTH + GAP
y = random.randint(0, HEIGHT)
r = random.randint(MIN_BALLOON_RADIUS, MAX_BALLOON_RADIUS)
id1 = c.create_oval(x-r,y-r,x+r,y+r, outline='purple4', fill='MediumPurple2')
balloon_id.append(id1)
balloon_radius.append(r)
balloon_speed.append(random.randint(1, MAX_BALLOON_SPEED))
def move_balloons():
for i in range(len(balloon_id)):
c.move(balloon_id[i], -balloon_speed[i], 0)
It throws out these errors for create_balloon():
File "C:\Users\xxx\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 2334, in create_oval
return self._create('oval', args, kw)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 2319, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: invalid command name ".55505712"
And this error for move_balloon():
File "C:\Users\xxx\Documents\Varsity\xxx\Balloon Killer - 19342306.py", line 128, in <module>
move_balloons()
File "C:\Users\xxx\Documents\Varsity\xxx\Balloon Killer - 19342306.py", line 66, in move_balloons
c.move(balloon_id[i], -balloon_speed[i], 0)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 2430, in move
self.tk.call((self._w, 'move') + args)
_tkinter.TclError: invalid command name ".42332976"

Related

KeyError: 'datapath' with Matplotlib

I am getting an error when trying to run code and am unsure how to solve the issue. I am unsure what this datapath is and the error is coming straight from the matplotlib package. Any help is greatly appreciated. Here is the error I am getting:
running API pyqt5
using configuration at /home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/image_analyzer.conf
no Pyro installed. Use dummy event handler.
/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/mplwidget.py:123: MatplotlibDeprecationWarning:
The _init_toolbar method was deprecated in Matplotlib 3.3 and will be removed two minor releases later. Please fully initialize the toolbar in your subclass' __init__; a fully empty _init_toolbar implementation may be kept for compatibility with earlier versions of Matplotlib.
super(Toolbar, self).__init__(*args, **kwargs)
Traceback (most recent call last):
File "start.py", line 5, in <module>
dmw, app, reuseapp = main.run_app()
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/main.py", line 552, in run_app
dmw = DesignerMainWindow()
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/main.py", line 33, in __init__
self.setupUi(self)
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/gui.py", line 333, in setupUi
self.main_area = self.setup_main_area(self.main_widget)
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/gui.py", line 306, in setup_main_area
center_area = self.setup_center_area(main_area)
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/gui.py", line 196, in setup_center_area
self.main_image_plot = MplWidget(self.tabs[0])
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/mplwidget.py", line 109, in __init__
self.mpl_toolbar = Toolbar(self.figCanvas, self)
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/mplwidget.py", line 123, in __init__
super(Toolbar, self).__init__(*args, **kwargs)
File "/home/.local/lib/python3.8/site-packages/matplotlib/backends/backend_qt5.py", line 681, in __init__
NavigationToolbar2.__init__(self, canvas)
File "/home/.local/lib/python3.8/site-packages/matplotlib/backend_bases.py", line 2913, in __init__
init()
File "/home/Desktop/Arbeit/image_analyzer_files/imageanalyser/qimageanalyser/mplwidget.py", line 140, in _init_toolbar
self.basedir = os.path.join(mpl.rcParams["datapath"], "images")
File "/home/.local/lib/python3.8/site-packages/matplotlib/__init__.py", line 623, in __getitem__
return dict.__getitem__(self, key)
KeyError: 'datapath'
start.py file:
#!/bin/env python
from qimageanalyser import main
import sys
dmw, app, reuseapp = main.run_app()
if "app" in globals() and not reuseapp:
sys.exit(app.exec_())
image_analyzer.conf file (I have to write more text to post this so I am writing more text here):
[Analysis Functions]
fitter = gaussian
analyser = absorption2
clearonnewrun = False
[General]
atom = Li6
nPics = 2
default_ref_roi_xi = 0
default_ref_roi_yi = 0
default_ref_roi_xf = 40
default_ref_roi_yf = 100
[Gui]
colorscale = jet
[Guppy]
pixelarea = 329.28e-12
magnification = 0.33
[Manta]
pixelarea = 64e-12
magnification = 2.5
[None]
pixelarea = 100e-12
magnification = 1
[Li6]
crosssection = 2.14949894091e-13
clebsch = 0.5
mass = 6
[Li7]
crosssection = 2.14949894091e-13
clebsch = 0.5
mass = 7
[Na]
crosssection = 1.6564257603715025E-13
clebsch = 1
mass = 23
mpl.rcParams["datapath"] was deprecated: https://github.com/matplotlib/matplotlib/pull/16417
Solution is to use
mpl.get_data_path()
instead of
mpl.rcParams["datapath"]

Getting a strange _tkinter.TclError: unknown option

I have made a small game where you progress through your life much like instlife but made in python with Tkinter. It is not complete and no where near being completed as i always get this same error.
This is my code
import tkinter
window = tkinter.Tk()
window.geometry("275x400")
window.title("Life")
year = 1980
age = 0
def ageButton():
global year
global age
year += 1
age += 1
yearText.configure(text=year)
dynamicText.configure("You are %d" %age)
yearText = tkinter.Label(window, text=year, anchor="n", width="270")
dynamicText = tkinter.Label(window, text="You are %d" %age, anchor="n",
width="270", height="495")
ageButton = tkinter.Button(window, text="Age", width="270",
command=ageButton)
ageButton.pack()
yearText.pack()
dynamicText.pack()
window.mainloop()
this is the error i get
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:\Users\Ed\Desktop\Lifee2\Life2.py", line 16, in ageButton
dynamicText.configure("You are %d" %age)
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1482, in configure
return self._configure('configure', cnf, kw)
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1472, in _configure
return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
File "C:\Users\Ed\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1460, in _getconfigure1
x = self.tk.splitlist(self.tk.call(*args))
_tkinter.TclError: unknown option "-You are 1"
When you call the configure method, you must tell tkinter what value you are changing. In your case you need to change this:
dynamicText.configure("You are %d" %age)
... to this:
dynamicText.configure(text="You are %d" %age)

'File not found' while importing gif for Tkinter.Label

I'm trying to import gif into a Tkinter.Label. I'm getting a file does not exist error. I have double checked the path and file name.
Below is the error message I get.
Traceback (most recent call last):
File "C:\Users\sachin\Desktop\Project California.py", line 39, in <module>
if __name__=='__main__': main()
File "C:\Users\sachin\Desktop\Project California.py", line 35, in main
feedback = Feedback(root)
File "C:\Users\sachin\Desktop\Project California.py", line 11, in __init__
self.logo = PhotoImage(file= "‪C:\\Users\\sachin\\Desktop\\signature.gif")
File "C:\Users\sachin\AppData\Local\Programs\Python\Python36
\lib\tkinter\__init__.py", line 3542, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "‪C:\Users\sachin\Desktop\signature.gif": no
such file or directory
Here is the code I used.
def __init__(self,master):
self.frame_header = ttk.Frame(master)
self.logo = PhotoImage(file= "‪C:\\Users\\sachin\\Desktop\\signature.gif")
ttk.Label(self.frame_header, image = self.logo)
I'm a noob in python programming. Apologies if the questions is too trivial.
I get the same error and I'm sure the path is right as well. In fact, it seems to find the file every other time it tries, with very similar code.
for r in range(0,5):
for c in range(1,4):
fn = file_name(c)
try:
photo = tk.PhotoImage(fn)
tk.Button(C, image = photo, width = "16", height = "16").grid(row = r,column = c)
except Exception as exception:

AssertionError in matplotlib animation

My problem is following:
I'm taking a data from files and want to make an animation of four plots at the same time: two colourbars and two lines.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as anim
import sys
begin = float(sys.argv[1])
end = float(sys.argv[2])
dataCl = np.loadtxt("file1.txt")
dataSS = np.loadtxt("file2.txt")
datajSR = np.loadtxt("file3.txt")
ibegin = 0
iend = 0
for i in range(len(dataCl[:,0])):
if np.abs(dataCl[i,0] - begin) < 1e-9:
ibegin = i
iend = i
while abs(dataCl[i,0] - end) >= 1e-9:
iend = iend + 1
i = i + 1
break
fig = plt.figure()
f, axarr = plt.subplots(2, 2)
temp = np.zeros((10,10))
Qs = axarr[0,0].imshow(temp,cmap = plt.cm.OrRd)
El = axarr[0,1].imshow(temp,cmap = plt.cm.OrRd)
SS, = axarr[1,0].plot([],[])
jSR, = axarr[1,1].plot([],[])
def init():
Qs.set_array(temp)
El.set_array(temp)
SS.set_data([],[])
jSR.set_data([],[])
return Qs,El,SS,jSR,
def animate(i):
a = 0
b = 0
dataQ = np.zeros((10,10))
dataE = np.zeros((10,10))
for j in range(100):
if b >= 10:
a = a + 1
b = 0
dataQ[a][b] = dataCl[i,2*j + 1]
dataE[a][b] = dataCl[i,2*(j+1)]
b = b + 1
Qs.set_array(dataQ)
El.set_array(dataE)
SS.set_data(dataSS[ibegin:ibegin+i,0],dataSS[ibegin:ibegin+i,1])
jSR.set_data(datajSR[ibegin:ibegin+i,0],datajSR[ibegin:ibegin+i,1])
return Qs,El,SS,jSR,
ani = anim.FuncAnimation(fig, animate, init_func = init, frames = iend-ibegin,interval=25, blit=True)
plt.show()
After running it shows these messages:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 236, in resize
self.show()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 239, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.py", line 421, in draw
self.figure.draw(self.renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 904, in draw
self.canvas.draw_event(renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 1544, in draw_event
self.callbacks.process(s, event)
File "/usr/lib/pymodules/python2.7/matplotlib/cbook.py", line 262, in process
proxy(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/cbook.py", line 192, in __call__
return mtd(*args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 273, in _end_redraw
self._post_draw(None, self._blit)
File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 220, in _post_draw
self._blit_draw(self._drawn_artists, self._blit_cache)
File "/usr/lib/pymodules/python2.7/matplotlib/animation.py", line 235, in _blit_draw
a.axes.draw_artist(a)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 2008, in draw_artist
assert self._cachedRenderer is not None
AssertionError
I cannot find a mistake in my code ;(
The error message might be backend and platform specific. As the error message seems to point to the blitting mechanism, you might want to try setting blit=False in FuncAnimation. Also, you might try some other backend to see if the problem persists. (Knowing your platform and matplotlib version might also help.)
Update: If setting blit=False, trying another backend, and updating matplotlib does not help, then a few suggestions:
Try to see manually if you code works with the initial data (init(); animate(0); fig.savefig("/tmp/test.png")) - if it throws an error, there is a static plotting problem to fix.
Now you initialize the plot twice (first in the code, then in init), you can take one away (e.g. do not define init_func)
Initializing the plots with [],[] leaves the scale uninitialized. You should probably use set_ylim, set_xlim with the plots and vmin, vmax keywords with the imshow images when you initialize them. (This could possibly have something to do with the exception you get!)

Weird error with .addstr() in a derwin()-object in Python Curses

I'm trying to segment one window in curses into several sub-windows (with derwin()).
The code creates two sub-windows and I can add a string; no problem with the first function. The second one is pretty much exactly the same but gives me an error when I try to add a string with addstr()
class Window(GUI):
'''
Window-object
'''
def __init__(self, y_max , x_max, y_pos , x_pos, Target, screen):
self.Win_Count = 0
self.y_pos = y_pos
self.x_pos = x_pos
self.y_max = y_max
self.x_max = x_max
self.parent = screen
self.Target = Target
#Window-Objects
self.Win = self.create_win_parent(y_pos)
self.Name_Win = self.create_name_win(self.Win)
self.IP_Win = self.create_ip_win(self.Win)
def create_win_parent(self, y_pos):
y_size = 1
x_size = self.x_max - self.x_pos
new_win_obj = self.parent.derwin(y_size, x_size, self.y_pos, 0)
self.Win_Count += 1
return new_win_obj
def create_name_win(self, Win_Obj):
x = Win_Obj.derwin(1,40, 0,0)
x.box()
x.addstr(0,5," CUSTOMER NAME ")
return x
def create_ip_win(self, Win_Obj):
x = Win_Obj.derwin(1,15, 0,41)
x.box()
x.addstr(0,5," IP-ADDRESS ")
return x
I'm getting this vague error:
Traceback (most recent call last):
File "./2pollng.py", line 229, in <module>
wrapper(main) # Enter the main loop
File "/usr/lib/python2.6/curses/wrapper.py", line 43, in wrapper
return func(stdscr, *args, **kwds)
File "./2pollng.py", line 222, in main
Main_App.Run(screen)
File "./2pollng.py", line 106, in Run
self.Create_Win(self.Inv.index(e), e)
File "./2pollng.py", line 90, in Create_Win
Win_Obj = Window(self.y_max, self.x_max, y_pos, x_pos, Target_x, self.screen)
File "./2pollng.py", line 141, in __init__
self.IP_Win = self.create_ip_win(self.Win)
File "./2pollng.py", line 160, in create_ip_win
x.addstr(0,5," IPADDRESS ")
_curses.error: addstr() returned ERR
def create_ip_win(self, Win_Obj):
x = Win_Obj.derwin(1,15, 0,41)
x.box()
x.addstr(0,5," IP-ADDRESS ")
return x
In this function Win_Obj.derwin(1,15, 0,41) shows that x-pos should between 0 and 14. While in the code addstr(0,5," IP-ADDRESS ") x starts at 5 and the length of string " IP-ADDRESS " is greater than (15-5). So you got the ERROR.
Not really sure about the specifics but it had ( as indicated by the interpreter, duh) something to do with the strings and them not having enough space in the subwindows i created.

Categories

Resources