I have a piece of code that queries a database from sqlite and passes each row through a function and then into a class both through *args. The problem is it adds a ,) to the end of it every time it passes through *args. I can get the 0th index every time after I pass it through to get rid of it but I don't always have something passing through *args in which case it comes up with an index out of range error. I figure there's a simpler way to go about this that I just don't know about. Any suggestions?
Not the exact code below but you get the idea of my problem.
from tkinter import *
from tkinter import ttk
class App(Tk):
def __init__(self,*args,**kwargs):
Tk.__init__(self)
btn1 = ttk.Button(self, command = self.EditLoadout)
btn1.pack()
def EditLoadout(self):
self.ticketquery = ['cat','hat','bat']
for x in self.ticketquery:
self.add_product(x)
def add_product(self, *args):
self.newprod = NewProduct(self,args)
self.newprod.pack(anchor=W)
class NewProduct(ttk.Frame):
def __init__(self,container,*args):
print(args)
Frame.__init__(self)
my_app = App()
my_app.mainloop()
CodePudding user response:
From what I can see from your code, your trying to add a new product by passing the variable args
from add_product
to the NewProduct __init__
function. Based on this, what you are doing may not be parsing the args as you think.
One *
operator is used to pack an uncertain amount of arguments into a Tuple object type. If you print a Tuple, it will look something similar to this: (1, 2, 3, 4)
When you pass a tuple through another function taking in *args
, you are only passing in one argument.
If you want to pass args
back as an uncertain amount of variables to another function, you can use *args
again. An example of this is shown below:
def tupleToList(*args):
print(list(args))
def passThroughFunction(*args):
print(args) # Prints (1, 2, 3, 4)
tupleToList(args) # Prints [(1, 2, 3, 4)]
tupleToList(*args) # Prints [1, 2, 3, 4]
passThroughFunction(1,2,3,4)