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.
Related
this is my code:
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
on hovering on on_enter_pressed function, it's showing function is not accessed and I'm getting the following error:
Traceback (most recent call last):
File "GUI.py", line 91, in <module>
app = ChatApplication()
File "GUI.py", line 15, in __init__
self._setup_main_window()
File "GUI.py", line 76, in _setup_main_window
self.msg_entry.bind("<Return>", self._on_enter_pressed)
AttributeError: 'ChatApplication' object has no attribute '_on_enter_pressed'
(I'm using tkinter in python to implement GUI.)
How can I solve this?
You have wrong indentations - _on_enter_pressed has to be outside __init__
def __init__(self):
# ... code ..
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
# outside `__init__`
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
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.
I am trying to create a tkinter label that changes color when clicked to show that it has been visited. I keep getting an attribute error saying that Show_Label has no attribute 'fg'. Please help! Here is the code being used.
class Sheet_Label(Label):
def __init__(self,master,text):
Label.__init__(self,master,text=text,cursor="hand2",font="Times 16 underline",fg="blue")
def button_click(event):
if self.fg =="blue":
self.fg = "purple"
else:
self.fg = "purple"
location = os.getcwd()
file = webbrowser.open_new(location + '\\' + "hello.txt")
self.bind("<Button-1>",func=button_click)
def sheets_view():
sheets_window = Toplevel(window)
hello = modules.Sheet_Label(master=sheets_window,text="Hello")
hello.pack(padx=10,pady=10)
sheets_window.title("Production Sheets")
sheets_window.focus()
x = (screen_width/2) - (500/2)
y = (screen_height/2) - (500/2)
sheets_window.geometry("%dx%d+%d+%d" % (500,500,x,y))
sheets_window.resizable(0,0)
Here is the error message:
Traceback (most recent call last):
File "C:\Users\napaf\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "inventory.py", line 311, in sheets_view
hello = modules.Sheet_Label(master=sheets_window,text="Hello")
File "C:\Users\napaf\Documents\Programming\adco_project\modules.py", line 24, in __init__
self.action = action
NameError: name 'action' is not defined
PS C:\Users\napaf\Documents\Programming\adco_project> python inventory.pyException in Tkinter callback
Traceback (most recent call last):
File "C:\Users\napaf\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\napaf\Documents\Programming\adco_project\modules.py", line 27, in button_click
if self.fg =="blue":
AttributeError: 'Sheet_Label' object has no attribute 'fg'
You aren't initializing self.fg until button_click has been called, but at that point it's too late because you're trying to reference self.fg before setting it.
Also, self.fg is not the same as the fg attribute when you create the widget (eg: Label(..., fg="blue"). If you want to get the value of the widget attribute you should use self.cget('fg') or use the shortcut self['fg']. If you want to set it from within the class itself you should use self.configure(fg="purple").
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.
Can't figure out what's wrong. All I know is that it doesn't execute. Find the trackback at the bottom.
EDIT: UPDATED, still doesn't run as should...
from livewires import games
SCREENWIDTH = 666
SCREENHEIGHT = 461
games.init (screen_width = SCREENWIDTH, screen_height = SCREENHEIGHT, fps = 100)
backgroundimage = games.load_image ("canvas.jpg", transparent = False)
games.screen.background = backgroundimage
class PhelpsAnimation(games.Animation):
thePhelpsFiles = ["Phelps1.jpg",
"Phelps2.jpg",
"Phelps3.jpg",
"Phelps4.jpg",
"Phelps5.jpg",
"Phelps6.jpg",
"Phelps7.jpg"]
def __init__(self, x = 333, y = 230.5):
super (PhelpsAnimation, self).__init__(x = x,
y = y,
images = PhelpsAnimation.images,
n_repeats = 1,
repeat_interval = 5)
games.screen.add(PhelpsAnimation())
games.screen.mainloop()
TRACEBACK:
Traceback (most recent call last):
File "C:\Users\COMPAQ\My Documents\Aptana Studio Workspace\PygameProject2\AstrocrashSoundandExplosion.py", line 28, in <module>
games.screen.add(PhelpsAnimation())
File "C:\Users\COMPAQ\My Documents\Aptana Studio Workspace\PygameProject2\AstrocrashSoundandExplosion.py", line 25, in __init__
images = PhelpsAnimation.images,
AttributeError: type object 'PhelpsAnimation' has no attribute 'images'
Exception AttributeError: "'PhelpsAnimation' object has no attribute '_gone'" in <bound method PhelpsAnimation.__del__ of <__main__.PhelpsAnimation object at 0x02600C90>> ignored
It's the images = PhelpsAnimation.thePhelpsfiles parameter. thePhelpsfiles is not an attribute of the PhelpsAnimation class you've defined. It should work if you change that to just images=thePhelpsfiles.