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.
Related
I'm trying to make Space Invaders as a project, I've watched videos on creating it and I have done quite a bit.
I've played around with it a lot, but there's always that one thing that goes wrong which messes up the entire thing.
This is my first post here, I'm not quite sure how to do this... let's see...
I keep facing this error, and it's not budging:
C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py:198: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
pygame.draw.rect(window, (0, 255, 0), (
Traceback (most recent call last):
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 415, in <module>
main_menu()
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 410, in main_menu
main()
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 377, in main
boss.shoot()
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 90, in shoot
laser = Laser(self.x - 20, self.y, self.laser_img)
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 109, in __init__
self.mask = pygame.mask.from_surface(self.img)
TypeError: argument 1 must be pygame.Surface, not None
Can anyone help me fix it? I'm not sure what to do here.
Look at this line here
boss = Boss(random.randrange(340, 360), random.randrange(-700, -100))
This is how you are instantiating your Boss
Now look at how you defined the init of your Boss class
def __init__(self, x, y, health=200):
self.x = x
self.y = y
self.health = health
self.ship_img = None
self.laser_img = None
self.lasers = []
self.cool_down_counter = 0
Notice that self.laser_img = None.
Now notice the error you have:
laser = Laser(self.x - 20, self.y, self.laser_img)
Your 3rd argument is None. Now look at the next part of your error:
self.mask = pygame.mask.from_surface(self.img)
self.img is actually None that is why you are getting an error.
Quite new to multiprocessing here. I have a code that runs two processes. One to continuously receive data blocks from the server and put it inside a queue and the other to remove the data blocks from the queue and process it.
Below is my client code:
import socket
import turtle
import multiprocessing
from multiprocessing import Process, Queue
from tkinter import *
class GUI:
def __init__(self, master):
rec_data = recv_data()
self.master = master
master.title("Collision Detection")
self.input_label = Label(root, text="Input all the gratings set straight wavelength values in nm")
self.input_label.grid(row=0)
self.core_string = "Core "
self.entries = []
self.label_col_inc = 0
self.entry_col_inc = 1
self.core_range = range(1, 5)
for y in self.core_range:
self.core_text = self.core_string + str(y) + '_' + '25'
self.core_label = Label(root, text=self.core_text)
self.entry = Entry(root)
self.core_label.grid(row=1, column=self.label_col_inc, sticky=E)
self.entry.grid(row=1, column=self.entry_col_inc)
self.entries.append(self.entry)
self.label_col_inc += 2
self.entry_col_inc += 2
self.threshold_label = Label(root, text="Threshold in nm")
self.entry_threshold = Entry(root)
self.threshold_label.grid(row=2, sticky=E)
self.entry_threshold.grid(row=2, column=1)
self.light_label = Label(root, text='Status')
self.light_label.grid(row=3, column=3)
self.canvas = Canvas(root, width=150, height=50)
self.canvas.grid(row=4, column=3)
# Green light
self.green_light = turtle.RawTurtle(self.canvas)
self.green_light.shape('circle')
self.green_light.color('grey')
self.green_light.penup()
self.green_light.goto(0, 0)
# Red light
self.red_light = turtle.RawTurtle(self.canvas)
self.red_light.shape('circle')
self.red_light.color('grey')
self.red_light.penup()
self.red_light.goto(40, 0)
self.data_button = Button(root, text="Get data above threshold", command=rec_data.getData)
self.data_button.grid(row=5, column=0)
class recv_data:
def __init__(self):
self.buff_data = multiprocessing.Queue()
self.p1 = multiprocessing.Process(target=self.recvData)
self.p2 = multiprocessing.Process(target=self.calculate_threshold)
self.host = '127.0.0.1'
self.port = 5001
self.s = socket.socket()
self.s.connect((self.host, self.port))
# function to receive TCP data blocks
def getData(self):
len_message = self.s.recv(4)
bytes_length = int(len_message.decode('utf-8')) # for the self-made server
recvd_data = self.s.recv(bytes_length)
self.buff_data.put(recvd_data)
self.p1.start()
self.p2.start()
self.p1.join()
self.p2.join()
def recvData(self):
len_message = self.s.recv(4)
while len_message:
bytes_length = int(len_message.decode('utf-8')) # for the self-made server
recvd_data = self.s.recv(bytes_length)
self.buff_data.put(recvd_data)
len_message = self.s.recv(4)
else:
print('out of loop')
self.s.close()
def calculate_threshold(self):
rmv_data = self.buff_data.get()
stringdata = rmv_data.decode('utf-8')
rep_str = stringdata.replace(",", ".")
splitstr = rep_str.split()
# received wavelength values
inc = 34
wav_threshold = []
for y in gui.entries:
straight_wav = float(y.get())
wav = float(splitstr[inc])
wav_diff = wav - straight_wav
if wav_diff < 0:
wav_diff = wav_diff * (-1)
wav_threshold.append(wav_diff)
inc += 56
threshold = float(gui.entry_threshold.get())
for x in wav_threshold:
if (x > threshold):
gui.red_light.color('red')
gui.green_light.color('grey')
else:
gui.red_light.color('grey')
gui.green_light.color('green')
# function to write into the file
def write_file(self, data):
with open("Output.txt", "a") as text_file:
text_file.write('\t'.join(data[0:]))
text_file.write('\n')
if __name__ == '__main__':
root = Tk()
gui1 = GUI(root)
root.mainloop()
The error I get is shown below:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:/Users/PycharmProjects/GUI/GUI_multiprocess.py", line 85, in getData
self.p2.start()
File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\context.py", line 326, in _Popen
return Popen(process_obj)
File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
reduction.dump(process_obj, to_child)
File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
TypeError: cannot pickle 'weakref' object
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\multiprocessing\spawn.py", line 126, in _main
self = reduction.pickle.load(from_parent)
EOFError: Ran out of input
What am I doing wrong here and how can I fix it? Any help is appreciated. Thank you!
I just came to the same traceback and managed to solve it. It was due to that an object had a running or exited Process as a variable and it was starting another Process using that object.
Problem
This is a minimal code to produce your error:
import multiprocessing
class Foo:
def __init__(self):
self.process_1 = multiprocessing.Process(target=self.do_stuff1)
self.process_2 = multiprocessing.Process(target=self.do_stuff2)
def do_multiprocessing(self):
self.process_1.start()
self.process_2.start()
def do_stuff1(self):
print("Doing 1")
def do_stuff2(self):
print("Doing 2")
if __name__ == '__main__':
foo = Foo()
foo.do_multiprocessing()
[out]:
Traceback (most recent call last):
File "myfile.py", line 21, in <module>
foo.do_multiprocessing()
File "myfile.py", line 11, in do_multiprocessing
self.process_2.start()
File "...\lib\multiprocessing\process.py", line 121, in start
self._popen = self._Popen(self)
File "...\lib\multiprocessing\context.py", line 224, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "...\lib\multiprocessing\context.py", line 327, in _Popen
return Popen(process_obj)
File "...\lib\multiprocessing\popen_spawn_win32.py", line 93, in __init__
reduction.dump(process_obj, to_child)
File "...\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
TypeError: cannot pickle 'weakref' object
Doing 1
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "...\lib\multiprocessing\spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "...\lib\multiprocessing\spawn.py", line 126, in _main
self = reduction.pickle.load(from_parent)
EOFError: Ran out of input
So the issue is that Foo contains also the running/exited process foo.process_1 when it starts foo.process_2.
Solution 1
Set foo.process_1 to None or something else. Or store the Processes somewhere else than in foo to prevent being passed when starting process_2.
...
def do_multiprocessing(self):
self.process_1.start()
self.process_1 = None # Remove exited process
self.process_2.start()
...
Solution 2
Remove the problematic variable (process_1) from pickling:
class Foo:
def __getstate__(self):
# capture what is normally pickled
state = self.__dict__.copy()
# remove unpicklable/problematic variables
state['process_1'] = None
return state
...
This seems to be problem in newer Python versions. My own code worked fine for 3.7 but failed due to this issue in 3.9.
I tested your code (from recv_data). Since you join the processes and need them, you should do the solution 2 or store the processes somewhere else than in recv_data. Not sure what other problems your code has.
I know there's been quite a few of these but after looking through them, I wasn't able to solve my issue. I'm also still learning Python so a simple mix up could be happening.
Thus far the error is being reached on the line with the constructed for loop.
# down
column = 2
grid = [ 10, 10 ]
while range > 0:
# grab at the top
cur = genes[((grid[1] - 1) * grid[0]) + column]
prev = cur
for a in range((grid[1] - 2), -1, -1):
# start one below from the top
cur = genes[(a * grid[0]) + column]
genes[(a * grid[0]) + column] = prev
prev = cur
# now apply the change back to the top
genes[((grid[1] - 1) * grid[0]) + column] = prev
if get_fitness(genes, grid) > fitness:
print("After Down")
board = Board(genes, grid)
board.print()
print("-------------------")
return
range -= 1
As requested
Traceback (most recent call last):
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/tetris.py", line 144, in test_double_block
self.solveDouble([4, 4])
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/tetris.py", line 167, in solveDouble
best = genetic.get_best(fnGetFitness, None, optimalFitness, geneset,
fnDisplay, custom_mutate=fnCustomMutate, custom_create=fnCreate, maxAge=10)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/genetic.py", line 105, in get_best
maxAge, poolSize):
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/genetic.py", line 131, in _get_improvement
child = new_child(parent, pindex, parents)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/genetic.py", line 102, in fnNewChild
return fnMutate(parent)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/genetic.py", line 74, in fnMutate
return _mutate_custom(parent, custom_mutate, get_fitness)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/genetic.py", line 47, in _mutate_custom
custom_mutate(childGenes)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/tetris.py", line 159, in fnCustomMutate
mutate(genes, grid, window)
File "/home/kyle/Documents/Books/GeneticAlgorithms/GA
Projects/Tetris/tetris.py", line 65, in mutate
for a in range((grid[1] - 2), -1, -1):
TypeError: 'int' object is not callable
You defined range as a number
while range > 0:
...
range -= 1
But you later used it as a function
for a in range(...):
Rename the range integer to something else
For example, you could do a backward for loop
for r in range(top_range, 0, -1):
...
my code seems to run fine with the brown square appearing in the blank window until I try and press one of the keys, when I do that nothing happens apart from an error message appearing. Any ideas?
from tkinter import *
x, y, a, b = 50, 50, 100, 100
d = None
vel_dic = {
"Left": ("left", -4, 0),
"Right": ("right", 4, 0),
"Down": ("down", 0, 4),
"Up": ("up", 0, -4)}
class Sprite:
def __init__(self):
self.move
self.x, self.y, self.a, self.b = 50, 50, 100, 100
self.d = 0
self.canvas = Canvas(tk, height = 600, width = 600)
self.canvas.grid(row=0, column=0, sticky = W)
self.coord = [self.x, self.y, self.a, self.b]
self.shape = self.canvas.create_rectangle(*self.coord, outline = "#cc9900", fill = "#cc9900")
def move():
if self.direction != 0:
self.canvas.move(self.rect, self.xv, self.yv)
tk.after(33, move)
def on_keypress(event):
self.direction, self.xv, self.yv = vel_dic[event.keysym]
def on_keyrelease(event):
self.direction = 0
tk = Tk()
tk.geometry("600x600")
sprite1 = Sprite()
tk.bind_all('<KeyPress>', sprite1.on_keypress)
tk.bind_all('<KeyRelease>', sprite1.on_keyrelease)
Error message when I press the right arrow key:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\idlelib\run.py", line 137, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\queue.py", line 172, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
TypeError: on_keypress() takes 1 positional argument but 2 were given
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\idlelib\run.py", line 137, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\queue.py", line 172, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\robsa\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
TypeError: on_keyrelease() takes 1 positional argument but 2 were given
When calling to function inside an object, self (the instance of the object) is sent as a first argument. You can undo that with some methods, staticmethod as the most common one, but that is not what you look for in that case.
The error you get indicates the interpreter sent this self parameter and the regular event parameter, but your method gets only one parameter, and can not handle them.
Make sure all your functions gets self (or any name you choose like inst) as a first parameter in addition to the other parameters:
def on_keyrelease(self, event):
Same goes for move and on_keypress.
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"