Tkinter Error on keypress - python

Code:
import tkinter
window = tkinter.Tk()
c = tkinter.Canvas(window, height=400, width=600, bg='green')
mid_x = 600 / 2
mid_y = 400 / 2
window.geometry("600x400")
window.title("window")
def ship_control(event):
pass
c.bind_all('<KeyPress-a>', ship_control)
def start():
global ship
rock_speed = 10
ship = c.create_oval(mid_x, mid_y, mid_x + 20, mid_y + 20, fill='red', outline='orange')
button_start = tkinter.Button(window, text='play', command=start)
button_start.pack()
c.pack()
Error:
>>>
>>> Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\idlelib\run.py", line 121, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "C:\Program Files\Python 3.5\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):
ValueError: invalid literal for int() with base 10: '??'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\Python 3.5\lib\tkinter\__init__.py", line 1534, in __call__
args = self.subst(*args)
File "C:\Program Files\Python 3.5\lib\tkinter\__init__.py", line 1252, in _substitute
e.num = getint_event(b)
File "C:\Program Files\Python 3.5\lib\tkinter\__init__.py", line 1231, in getint_event
return int(s)
SystemError: result with error in PyObject_Call
How to reproduce:
Open the program, press play then press a.
I have no idea what could be wrong altough I have tried searching on google.
I tried adding prints but they don't get executed.
Does anyone know why I get the error?

The problem was that I was using 3.5 instead of 3.4. Switching versions worked.

Related

controlling updown spinner elemnt using pywinauto

I am trying to control the value of a UpDown spinner element with pywinauto.
this is my element i want to control:
UpDown - 'Spinner' (L384, T624, R400, B642)
| | | | | ['Spinner', 'SpinnerUpDown', 'UpDown']
| | | | | child_window(title="Spinner", auto_id="68226", control_type="Spinner")
I am not sure how to get it's value and set it's value through pywinauto.
i have succeded doing it with button element, but the spinner element is not working while doing the examples and help i found on the internet.
my code goes like this:
from pywinauto.application import Application
app = Application(backend="uia").start('smcg2gui.exe')
# app.PololuSimpleMotorControlCenterG2.print_control_identifiers()
stop_motor = app.PololuSimpleMotorControlCenterG2.child_window(title="Stop motor", auto_id="stopMotorButton", control_type="Button")
speed_controller = app.PololuSimpleMotorControlCenterG2.child_window(title="Spinner", auto_id="7995854", control_type="Spinner")
speed_controller.get_value()
stop_motor.click()
print("done")
and i am getting this error:
Traceback (most recent call last):
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 250, in __resolve_control
ctrl = wait_until_passes(
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\timings.py", line 458, in wait_until_passes
raise err
pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\owner\Desktop\try.py", line 12, in <module>
speed_controller.get_value()
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 379, in __getattribute__
ctrls = self.__resolve_control(self.criteria)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 261, in __resolve_control
raise e.original_exception
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\timings.py", line 436, in wait_until_passes
func_val = func(*args, **kwargs)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\application.py", line 222, in __get_ctrl
ctrl = self.backend.generic_wrapper_class(findwindows.find_element(**ctrl_criteria))
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\findwindows.py", line 87, in find_element
raise ElementNotFoundError(kwargs)
pywinauto.findwindows.ElementNotFoundError: {'title': 'Spinner', 'auto_id': '7995854', 'control_type': 'Spinner', 'top_level_only': False, 'parent': <uia_element_info.UIAElementInfo - 'Pololu Simple Motor Control Center G2', WindowsForms10.Window.8.app.0.33c0d9d, 1835472>, 'backend': 'uia'}
so i tried doing it with wrapper_object:
from pywinauto.application import Application
app = Application(backend="uia").start('smcg2gui.exe')
# app.PololuSimpleMotorControlCenterG2.print_control_identifiers()
stop_motor = app.PololuSimpleMotorControlCenterG2.child_window(title="Stop motor", auto_id="stopMotorButton", control_type="Button")control_type="Button")
speed_controller = app.PololuSimpleMotorControlCenterG2.UpDown.wrapper_object()
print(speed_controller.iface_value.CurrentValue)
stop_motor.click()
print("done")
and got this:
Traceback (most recent call last):
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\uia_defines.py", line 234, in get_elem_interface
iface = cur_ptrn.QueryInterface(cls_name)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\comtypes\__init__.py", line 1197, in QueryInterface
self.__com_QueryInterface(byref(iid), byref(p))
ValueError: NULL COM pointer access
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\owner\Desktop\try.py", line 12, in <module>
print(speed_controller.iface_value.CurrentValue)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uiawrapper.py", line 132, in __get__
value = self.fget(obj)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\controls\uiawrapper.py", line 252, in iface_value
return uia_defs.get_elem_interface(elem, "Value")
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\pywinauto\uia_defines.py", line 236, in get_elem_interface
raise NoPatternInterfaceError()
pywinauto.uia_defines.NoPatternInterfaceError
i am a bit lost.
Thank you very much

Error when following Python Password Vault tutorial : "cryptography.exceptions.InvalidSignature: Signature did not match digest."

I'm a beginner and I followed this YT tutorial and happened to encountered an error he didn't have.
https://youtu.be/QBSAfahLuSk?t=1264
So what happened was, after I changed the master password, my password vault is empty. it didn't carry over the previous master password's passwords vault and produced numbers of error in the output.
A lot of the outputs was error in tkinter fernet but one of it said it was something wrong with this code
def decrypt(message: bytes, token: bytes) -> bytes:
return Fernet(token).decrypt(message)
if cursor.fetchall() is not None:
i = 0
while True:
cursor.execute("SELECT * FROM vault")
array = cursor.fetchall()
if (len(array) == 0):
break
lbl1 = Label(second_frame, text=(decrypt(array[i][1], encryptionKey)))
lbl1.grid(column=0, row=i + 3)
lbl2 = Label(second_frame, text=(decrypt(array[i][2], encryptionKey)))
lbl2.grid(column=1, row=i + 3)
lbl3 = Label(second_frame, text=(decrypt(array[i][3], encryptionKey)))
lbl3.grid(column=2, row=i + 3)
btn = Button(second_frame, text="Delete", command=partial(removeEntry, array[i][0]))
btn.grid(column=6, row=i + 3, pady=10)
i = i + 1
cursor.execute("SELECT * FROM vault")
if len(cursor.fetchall()) <= i:
break
here's the full error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\cryptography\fernet.py", line 133, in _verify_signature
h.verify(data[-32:])
File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\cryptography\hazmat\primitives\hmac.py", line 72, in verify
ctx.verify(signature)
File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\cryptography\hazmat\backends\openssl\hmac.py", line 85, in verify
raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\Lib\tkinter\__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "c:\Users\user\desktop\opensesame.py", line 150, in done
vaultScreen()
File "c:\Users\user\desktop\opensesame.py", line 327, in vaultScreen
lbl1 = Label(second_frame, text=(decrypt(array[i][1], encryptionKey)))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\user\desktop\opensesame.py", line 33, in decrypt
return Fernet(token).decrypt(message)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\cryptography\fernet.py", line 90, in decrypt
return self._decrypt_data(data, timestamp, time_info)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\cryptography\fernet.py", line 151, in _decrypt_data
self._verify_signature(data)
File "C:\Users\user\AppData\Roaming\Python\Python311\site-packages\cryptography\fernet.py", line 135, in _verify_signature
raise InvalidToken
cryptography.fernet.InvalidToken

Exception in Tkinter callback, KeyError: 0

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\range.py", line 351, in get_loc
return self._range.index(new_key)
ValueError: 0 is not in range
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "<ipython-input-18-518ef7ebbd84>", line 4, in myClick2
a.plot(p1.total_payoff()[0],p1.total_payoff()[1])
File "<ipython-input-10-57724152e4a6>", line 59, in total_payoff
prices = self.option_payoff()[0]
File "<ipython-input-10-57724152e4a6>", line 47, in option_payoff
temppayoff += callpayoff(i,j.get_strike(),j.find_bidask()[1])*j.get_quantity()
File "<ipython-input-6-59b6ad5c0680>", line 28, in find_bidask
bid = data['bid'][0]
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py", line 853, in __getitem__
return self._get_value(key)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py", line 961, in _get_value
loc = self.index.get_loc(label)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\indexes\range.py", line 353, in get_loc
raise KeyError(key) from err
KeyError: 0
This is the error message I am getting when I try to execute a function by clicking a TKinter button. The function is below, basically it takes some data (x, y), and plots it with matplotlib.
def myClick2():
f = Figure(figsize=(4,4), dpi=100)
a = f.add_subplot(111)
a.plot(p1.total_payoff()[0],p1.total_payoff()[1])
a.grid(True, which='both')
a.axhline(y=0, color='k')
a.axvline(x=0, color='k')
canvas = FigureCanvasTkAgg(f, master=root)
canvas.draw()
canvas.get_tk_widget().grid(row = 8, column = 1)
The error is saying that "total_payoff", which calls "option_payoff", which calls "find_bidask" is leading to the error. Specifically, the part which I assign bid = data['bid'][0].
def find_bidask(self):
if str.upper(self.cp) == 'C':
data = self.data['calls']
else:
data = self.data['puts']
data = data[data['contractSymbol']==self.symbol].reset_index(drop=True)
bid = data['bid'][0]
ask = data['ask'][0]
However, when I run this separately outside of TKinter, it produces no error, and ['bid'][0] is available as a value. I don't understand what is wrong with my code - is it something in the tkinter myclick2 function that is wrong?

Why is my python code returning an UnboundLocalError?

I am trying to make a Tkinter Python CPS Test program, but it keeps returning an error that my variables time and count are being referenced before assignment. Why does this happen? I shall put my entire code up and also the error message. Help!
from tkinter import *
from time import sleep
tab = Tk()
tab.geometry('500x500')
count = 0
time = 0
def countTime():
sleep(1)
time = time + 1
tab.resizable(0, 0)
tab.title("")
def click():
count = count + 1
if time == 10:
cps = count/time
Label(tab, text = str(cps) + " clicks per second!", font = "helvetica 30 bold underline italic", padx = 50, pady = 50).pack()
btn = Button(tab, text = 'Click Me!', font = "helvetica 24 bold", command = click, background = "blue", activebackground = "yellow").pack()
for i in range(0, 10):
countTime()
And here is the error:
Traceback (most recent call last):
File "main.py", line 19, in <module>
btn = Button(tab, text = 'Click Me!', font = "helvetica 24 bold", command = click, background = "royal blue1", activ
Traceback (most recent call last):
File "main.py", line 21, in <module>
countTime()
File "main.py", line 9, in countTime
time += 1
UnboundLocalError: local variable 'time' referenced before assignment
 Exception in Tkinter callback
Traceback (most recent call last):
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "main.py", line 14, in click
count += 1
UnboundLocalError: local variable 'count' referenced before assignment
Exception in Tkinter callback
Traceback (most recent call last):
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "main.py", line 14, in click
count += 1
UnboundLocalError: local variable 'count' referenced before assignment
Exception in Tkinter callback
Traceback (most recent call last):
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "main.py", line 14, in click
count += 1
UnboundLocalError: local variable 'count' referenced before assignment
Traceback (most recent call last):
File "main.py", line 19, in <module>
btn = Button(tab, text = 'Click Me!', font = "helvetica 24 bold", command = click, background = "royal blue1", activ
Traceback (most recent call last):
File "main.py", line 21, in <module>
countTime()
File "main.py", line 9, in countTime
time += 1
UnboundLocalError: local variable 'time' referenced before assignment
 Exception in Tkinter callback
Traceback (most recent call last):
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "main.py", line 14, in click
count += 1
UnboundLocalError: local variable 'count' referenced before assignment
Exception in Tkinter callback
Traceback (most recent call last):
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "main.py", line 14, in click
count += 1
UnboundLocalError: local variable 'count' referenced before assignment
Exception in Tkinter callback
Traceback (most recent call last):
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "main.py", line 14, in click
count += 1
UnboundLocalError: local variable 'count' referenced before assignment
Traceback (most recent call last):
File "main.py", line 21, in <module>
countTime()
File "main.py", line 9, in countTime
time = time + 1
UnboundLocalError: local variable 'time' referenced before assignment
Also, I want to make the button change color on click also, so maybe you could help out with that too? I would prefer if every possible error would be pointed out so I could know in advance. Thanks!

Turtle bgpic() not displaying image and giving me these error messages…?

I am trying to get Turtle-graphics to display a background image.
Here's my code:
import turtle
from turtle import *
from appJar import gui
...
turtle.setup(900,700) #windowsize
Ian = turtle.Turtle()
Ian.hideturtle()
Ian.screen.title("Arp Convertor")
Ian.screen.bgcolor("#4a4a54")
Ian.screen.bgpic('Backwslots2.gif')
Ian.speed(0)
Ian.penup() #dont draw
Ian.goto(-430,250) #where we'll start drawing
My image is the right size, exactly 900x700 in the current dir (same as my .py file). But the bgpic() line is giving me these errors.
> Exception in Tkinter callback Traceback (most recent call last):
> File
> "C:\Users\Ian\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py",
> line 1705, in __call__
> return self.func(*args) File "D:\Midipy\appJar\appjar.py", line 3574, in <lambda>
> return lambda *args: funcName(param) File "midipy.py", line 21, in openthefile
> convertthefile(btn) File "midipy.py", line 141, in convertthefile
> Ian.screen.bgpic('Backwslots2.gif') File "C:\Users\Ian\AppData\Local\Programs\Python\Python37-32\lib\turtle.py",
> line 1482, in bgpic
> self._setbgpic(self._bgpic, self._bgpics[picname]) File "C:\Users\Ian\AppData\Local\Programs\Python\Python37-32\lib\turtle.py",
> line 738, in _setbgpic
> self.cv.itemconfig(item, image=image)

Categories

Resources