Updating Tkinter Treeview with SQLite database - python-3.x

I am trying to update my treeview by using a delete function but I cannot get the information to transfer over. I have old name and old phone number, and I want to update them with new name and new phone number. I keep encountering the same issue. Here is my code below:
def update():
update_opt = Toplevel()
update_opt.title("Updating")
# grabbing old values from table
old_name = StringVar(update_opt, tree1.item(tree1.focus())['values'][0])
old_phone = StringVar(update_opt, tree1.item(tree1.focus())['values'][1])
Phone = StringVar(update_opt)
Name = StringVar(update_opt)
# creating labels for new/old values
lbl1 = Label(update_opt, text="Old Name: ").grid(row=0,column=1)
pre_name = Entry(update_opt, textvariable=old_name,state='readonly')
pre_name.grid(row=0,column=2)
lbl2 = Label(update_opt, text="New name: ").grid(row=1,column=1)
new_name = Entry(update_opt, textvariable=Name).grid(row=1,column=2)
#New_Name = new_name.get()
lbl3 = Label(update_opt, text="Old Phone Number: ").grid(row=2,column=1)
pre_phonenumber = Entry(update_opt, textvariable=old_phone, state='readonly')
pre_phonenumber.grid(row=2,column=2)
lbl4 = Label(update_opt, text="New Phone Number: ").grid(row=3,column=1)
new_phonenumber = Entry(update_opt, textvariable=Phone).grid(row=3,column=2)
#New_Number = new_phonenumber.get()
save_btn = ttk.Button(update_opt, text="Save Changes",
command = lambda:save_changes(new_name,old_name,
new_phonenumber,
old_phone))
save_btn.grid(row=4,column=2,sticky=W)
update_opt.mainloop()
def save_changes(new_name, old_name, new_phonenumber, old_phone):
selected_item = tree1.selection()
#gets the values associated with the selected item
values = (tree1.item(selected_item)['values'])
query = 'UPDATE clients SET name=?, phone=? WHERE name=? AND phone=?'
parameters=(new_name, new_phonenumber, old_name, old_phone)
conn = sq.connect('Clients.db')
c3 = conn.cursor()
c3.execute(query, (new_name, new_phonenumber, values,))
conn.commit()
tree1.delete(selected_item)
edit_wind.destroy()
display_clients()
I keep getting this error:
xception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/home/zizibaby/Desktop/SD Functions .py", line 77, in <lambda>
old_phone))
File "/home/zizibaby/Desktop/SD Functions .py", line 98, in save_changes
c3.execute(query, (new_name, new_phonenumber, values,))
sqlite3.ProgrammingError: Incorrect number of bindings supplied.
The current statement uses 4, and there are 3 supplied.
I added the tree.selection to actually grab the value however it's not working. I tried .get() function but it say NoneType for get().
Please, any help?

Related

How do you a change guild icon from a list of randomly selected local image's?

I have been trying to make a Slash command to change the Guild's icon. The icon it changes it to is picked from a list of icons at random but I'm getting this error and have no idea what it means:
Ignoring exception in command icon_change: Traceback (most recent call last): File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 1053, in _call_with_hooks
await callback(*args) File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 1135, in call_invoke_slash
await self.invoke_slash(interaction, **kwargs) File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 1228, in invoke_slash
await self.callback(interaction, **kwargs) File "C:\PC Code\Python\Nextcord - Bots\utilities 2.6 - NextCord.py", line 255, in icon_change
await interaction.guild.edit(icon=ficon) File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\guild.py", line 1570, in edit
fields['icon'] = utils._bytes_to_base64_data(icon) File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\utils.py", line 495, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data) File "C:\Users\Leo\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\utils.py", line 481, in _get_mime_type_for_image
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'): TypeError: startswith first arg must be str or a tuple of str, not bytes
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes
Here is the code I currently have:
#bot.slash_command(description="Change server icon")
#application_checks.is_owner()
async def icon_change(interaction : Interaction):
with open('C:\Server_Icons\Logoaa.png', 'rb') as Iconaa:
icona = Iconaa.read()
with open('C:\Server_Icons\Logocc.png', 'rb') as Iconcc:
iconc = Iconcc.read()
with open('C:\Server_Icons\Logodd.png', 'rb') as Icondd:
icond = Icondd.read()
with open('C:\Server_Icons\Logoff.png', 'rb') as Iconff:
iconf = Iconff.read()
with open('C:\Server_Icons\Logohh.png', 'rb') as Iconhh:
iconh = Iconhh.read()
iconch = ['icona', 'iconc', 'icond', 'iconf', 'iconh']
ficon = random.choice(iconch)
await interaction.guild.edit(icon=ficon)
Any help would be appreciated.
This can be fixed by converting the image to a byte array using 'bytearray()'
Example:
with open('C:\Images\Image.png', 'rb') as Image:
a = Image.read()
imageA = bytearray(a)
Fixed code:
#bot.slash_command(description="Change server icon")
#application_checks.is_owner()
async def icon_change(interaction : Interaction):
with open('C:\Server_Icons\Logoaa.png', 'rb') as Iconaa:
iconaaa = Iconaa.read()
icona = bytearray(iconaaa)
with open('C:\Server_Icons\Logocc.png', 'rb') as Iconcc:
iconccc = Iconcc.read()
iconc = bytearray(iconccc)
with open('C:\Server_Icons\Logodd.png', 'rb') as Icondd:
iconddd = Icondd.read()
icond = bytearray(iconddd)
with open('C:\Server_Icons\Logoff.png', 'rb') as Iconff:
iconfff = Iconff.read()
iconf = bytearray(iconfff)
with open('C:\Server_Icons\Logohh.png', 'rb') as Iconhh:
iconhhh = Iconhh.read()
iconh = bytearray(iconhhh)
iconch = [icona, iconc, icond, iconf, iconh]
ficon = random.choice(iconch)
await interaction.send(f"Icon changed!")
await interaction.guild.edit(icon=ficon)

why i got "rospy.ServiceException"?

i am working with ros about 3 month! I work on a robot controller.
i got error in ui about this client:
import sys
import rospy
from database_helper.srv import get_moves, get_movesRequest, get_movesResponse, get_move
def get_data(name: str):
"""This function can extract model names from DB"""
try:
rospy.init_node("get_moves_client")
except:
pass
rospy.wait_for_service('get_moves')
try:
moves = rospy.ServiceProxy('get_moves', get_moves)
except rospy.ServiceException as e:
print(31)
print(e)
return
id = 0
try:
for i in (moves(True).moves):
if i.name == name:
id = i.id
#print(id)
break
except:
print(43)
return
rospy.wait_for_service('get_move')
move = rospy.ServiceProxy('get_move', get_move)
wps = move(id).waypoints
list_of_data = []
try:
for i in range(len(wps)):
print(i)
data = {}
data['x_traj'] = wps[i].x
data['y_traj'] = wps[i].y
data['z_traj'] = wps[i].z
data['time_tarj'] = wps[i].displacement_time_to_next_waypoint
data['order_traj'] = wps[i].order
data['pitch_traj'] = wps[i].pitch
data['roll_traj'] = wps[i].roll
data['yaw_traj'] = wps[i].yaw
data['focus_camer'] = wps[i].camera_focus
data['iris_camera'] = wps[i].camera_iris
data['rail_direction'] = wps[i].rail_direction
data['rail_speed'] = wps[i].rail_speed
data['zoom_camera'] = wps[i].camera_zoom
data['rail_time'] = wps[i].rail_time
data['rail_displacement'] = wps[i].rail_displacement
list_of_data.append(data)
except rospy.ServiceException:
pass
print(list_of_data)
return list_of_data
this client can get data from DB and save with dict and save all dict in a list.
i most write "try/except" and i see 43 number! so i know my except is in for i in range(len(wps)):
the amazing point is, i can run this script and i get answer, but if call this script in my ui, after i using save waypoint and i try to load waypoint, i get ServiceException!
my "add_move.py" code:
from typing import List, Dict
import rospy
from database_helper.srv import add_move
from database_helper.msg import move, waypoint
def _add_move(name: str, wp: List[Dict]):
"""This Function can for send insert query for DB"""
rospy.init_node('add_move_client', anonymous=True)
rospy.wait_for_service('add_move')
_move = move()
_move.name = name
for i in range(len(wp)):
_waypoint = waypoint()
_waypoint.x = wp[i]['x_traj']
_waypoint.y = wp[i]['y_traj']
_waypoint.z = wp[i]['z_traj']
_waypoint.displacement_time_to_next_waypoint = wp[i]['time_tarj']
_waypoint.pitch = wp[i]['pich_traj']
_waypoint.roll = wp[i]['roul_traj']
_waypoint.yaw = wp[i]['ya_traj']
_waypoint.camera_focus = wp[i]['focus_camer']
_waypoint.camera_iris = wp[i]['iris_camera']
_waypoint.camera_zoom = wp[i]['zoom_camera']
_waypoint.rail_speed = wp[i]['speed_rail']
_waypoint.rail_displacement = wp[i]['disp_or_time_rail']
_waypoint.rail_direction = wp[i]['direction_rail']
_move.waypoints.append(_waypoint)
add = rospy.ServiceProxy('add_move', add_move)
return add(_move).id
if __name__ == "__main__":
from random import randint
data = {'x_traj': 12, 'y_traj': 12, 'z_traj': 33, 'time_tarj': 11,
'pich_traj': 13, 'roul_traj': 43, 'ya_traj': 21,
'focus_camer': 11, 'iris_camera': 55, 'zoom_camera': 32,
'disp_or_time_rail': 21, 'speed_rail': 109, 'direction_rail':44,
'joint1_slider': 12, 'joint2_slider': 666, 'joint3_slider': 567,
'joint4_slider': 32, 'joint5_slider': 79, 'joint6_spin': 100
}
wp = []
wp.append(data)
print(_add_move("t1", wp))
my error in terminal without "try/except" is:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 223, in deserialize_messages
msg_queue.append(data.deserialize(q))
File "/home/ajax/Documents/iotive/devel/lib/python3/dist-packages/database_helper/srv/_get_moves.py", line 247, in deserialize
val2 = database_helper.msg.waypoint()
File "/home/ajax/Documents/iotive/devel/lib/python3/dist-packages/database_helper/msg/_waypoint.py", line 95, in __init__
self.rail_displacement = 0
AttributeError: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_base.py", line 735, in receive_once
p.read_messages(b, msg_queue, sock)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 361, in read_messages
rospy.msg.deserialize_messages(b, msg_queue, self.recv_data_class, queue_size=self.queue_size, max_msgs=1, start=1) #rospy.msg
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/msg.py", line 245, in deserialize_messages
raise genpy.DeserializationError("cannot deserialize: %s"%str(e))
genpy.message.DeserializationError: cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 522, in call
responses = transport.receive_once()
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_base.py", line 751, in receive_once
raise TransportException("receive_once[%s]: DeserializationError %s"%(self.name, str(e)))
rospy.exceptions.TransportException: receive_once[/get_moves]: DeserializationError cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./benchmark_new_version_4_1.py", line 730, in get_data_query
self.wp_saver = get_data(response)
File "/home/ajax/Documents/iotive/src/gui/ui/scripts/get_moves_clinet.py", line 36, in get_data
for i in (moves(True).moves):
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 442, in __call__
return self.call(*args, **kwds)
File "/opt/ros/noetic/lib/python3/dist-packages/rospy/impl/tcpros_service.py", line 532, in call
raise ServiceException("transport error completing service call: %s"%(str(e)))
rospy.service.ServiceException: transport error completing service call: receive_once[/get_moves]: DeserializationError cannot deserialize: 'waypoint' object attribute 'rail_displacement' is read-only
what is my wrong?
srv/get_move:
int32 id
---
waypoint[] waypoints
srv/get_moves:
bool add_waypoints
---
move[] moves
msg/move:
int32 id
string name
waypoint[] waypoints
msg/waypoint:
int32 id
int32 order
float64 x
float64 y
float64 z
float64 roll
float64 pitch
float64 yaw
int32 camera_focus
int32 camera_iris
int32 camera_zoom
int32 rail_displacement
int32 rail_time
int32 rail_speed
bool rail_direction
int32 displacement_time_to_next_waypoint
So we need to remove service variables when we do not have anything else.
like this:
rospy.wait_for_service('get_moves')
moves = rospy.ServiceProxy('get_moves', get_moves)
id = 0
for i in (moves(True).moves):
if i.name == name:
id = i.id
#print(id)
break
rospy.wait_for_service('get_move')
move = rospy.ServiceProxy('get_move', get_move)
wps = move(id).waypoints
list_of_data = []
for i in range(len(wps)):
print(i)
data = {}
data['order_traj'] = wps[i].order
data['x_traj'] = wps[i].x
data['y_traj'] = wps[i].y
data['z_traj'] = wps[i].z
data['time_tarj'] = wps[i].displacement_time_to_next_waypoint
data['order_traj'] = wps[i].order
data['pitch_traj'] = wps[i].pitch
data['roll_traj'] = wps[i].roll
data['yaw_traj'] = wps[i].yaw
data['focus_camer'] = wps[i].camera_focus
data['iris_camera'] = wps[i].camera_iris
data['rail_direction'] = wps[i].rail_direction
data['rail_speed'] = wps[i].rail_speed
data['zoom_camera'] = wps[i].camera_zoom
data['rail_time'] = wps[i].rail_time
data['rail_displacement'] = wps[i].rail_displacement
list_of_data.append(data)
del move
del moves
print(list_of_data)
return list_of_data
I discovered this last night!

IMAP4LIB When using the store command I get the error "BAD [b'Could not parse command']"

I am new to all of this so I'm sorry if I mess this up or have already made a mess. I have two classes a GUI and my MailSorter class in the GUI class I have method which logins, then one that fetches all the EmailIds then finally fetches all the From emails and stores it in a dict. which stores the From email and amount of times it appears and an array with the From email and the ID.
def fetchFrom(self,emailIDs):
EmailAmount = dict()
Email = []
count = 0
for emailId in emailIDs:
#Converts email into string
result2,email_data = self.mail.fetch(emailId,'(RFC822)')
try:
raw_email = email_data[0][1].decode("utf-8")
email_message = email.message_from_string(raw_email)
#Fetches email address sent from
From = email_message["From"]
Email.append((From,emailId))
#print(From)
if From in EmailAmount:
EmailAmount[From] = EmailAmount[From] + 1
else:
EmailAmount[From] = 1
count += 1
if count > 10:
break
except Exception as e:
self.log.append((emailId,e))
def mainScreenInterface(self):
#Process
print("Loading program")
EmailIds = self.Mail.fetchEmailId()
EmailDict, self.EmailArray = self.Mail.fetchFrom(EmailIds)
self.master.geometry("750x600")
self.master.title("Main Screen")
self.destoryWidget()
#New Frame
self.mainScreen = tk.Frame(self.master)
self.mainScreen.pack()
#Labels
mainText = tk.Label(self.mainScreen,text = "All Emails")
mainText.config(font=("Courier","25"))
#Buttons
delete = tk.Button(self.mainScreen,text="Delete", command = self.Delete)
deleteAll = tk.Button(self.mainScreen,text="Delete All", command = self.DeleteAll)
Help = tk.Button(self.mainScreen,text="Help", command = self.Help_)
#Scrollbar
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side="right",fill="y")
#Listbox
self.listbox = tk.Listbox(root,width = root.winfo_screenwidth(), height = 25)
#Attach a scrool wheel to the listbox
self.listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.listbox.yview)
#Add items to the list box
count = 1
for x,y in EmailDict.items():
self.listbox.insert(count,(x,y))
count += 1
#Placement
paddingValue = 40
mainText.pack(side="top")
self.listbox.pack(side="top")
delete.pack(side="left",padx=paddingValue)
deleteAll.pack(side="left",padx=paddingValue)
Help.pack(side="left",padx=paddingValue)
def Delete(self):
emailName = self.listbox.get(tk.ANCHOR)[0]
self.Mail.deleteEmail(emailName,self.EmailArray)
So the fetchFrom is from the mailSorter class and the other two are the GUI class, when I call the deleteEmail I get the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\******\Desktop\Email Sorter v3.py", line 197, in Delete
self.Mail.deleteEmail(emailName,self.EmailArray)
File "C:\Users\******\Desktop\Email Sorter v3.py", line 66, in deleteEmail
self.mail.store(Id[1].strip(), '+X-GM-tk.LabelS', '\\Trash')
File "C:\Python\lib\imaplib.py", line 840, in store
typ, dat = self._simple_command('STORE', message_set, command, flags)
File "C:\Python\lib\imaplib.py", line 1196, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Python\lib\imaplib.py", line 1027, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.IMAP4.error: STORE command error: BAD [b'Could not parse command']
but when I run it as a text base with no GUI and use an example email it all works fine:
test = MailSorter("hamadnassor5#gmail.com","snerfulbubble1.")
test.login()
EmailIds = test.fetchEmailId()
EmailDict, EmailArray = test.fetchFrom(EmailIds)
test.displayEmails(EmailDict)
test.deleteEmail("Xbox <Xbox#outlook.com>",EmailArray)
test.closeCon()
DeleteMail code
def deleteEmail(self, emailName, EmailArray):
for Id in EmailArray:
if Id[0] == emailName:
print(Id[0])
print(emailName)
print(Id[1])
self.mail.store(Id[1].strip(), '+X-GM-tk.LabelS', '\\Trash')

having issue when try to getting selected value in optionmenu in tkinter(python3)

I am trying to get value which is selected from the list in drop-down menu but having this error
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python36\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Python36\lib\tkinter\__init__.py", line 3436, in __call__
self.__callback(self.__value, *args)
TypeError: changeInLymph() takes 0 positional arguments but 1 was given
My code is:
# dropDown options
def changeInLymph():
data = "you selected the option " + var10.get()
label10.config(text=data)
var10 = StringVar()
choices = ['bean', 'oval', 'round']
# set the default option
popupMenu = OptionMenu(f1, var10, *choices ).grid(row = 20, column =5)
Label(f1, text="Choose a dish").grid(row = 19, column = 5)
label10 = Label(f1).grid(row=21,column=1)
where i am doing wrong please help anybody.

Problem extracting values from mysql Python

I get an error when I'm trying to convert a field from a mysql query into a variable, my code it's like:
def GetCompanyswithNoResult():
global tabla_db
connection = mysql.connector.connect
mycursor = connection.cursor()
sql = "SELECT * FROM "+ tabla_db +" WHERE RESULT = 0"
mycursor.execute(sql)
myresult = mycursor.fetchone()
ID = myresult[0]
Location = myresult[2]
Market = myresult[3] + " into " + myresult[4]
return [ID, Location, Market]
ID, League, Match = GetMatcheswithNoResult()
the error message that return it's:
Traceback (most recent call last):
File, line 248, in
ID, League, Match = GetCompanywithNoResult()
File , line 123, in GetCompanywithNoResult
ID = myresult[0]
TypeError: 'NoneType' object is not subscriptable
I need some help...
How can I export these values without error?

Resources