Home > Net >  How to have another argument when we alread have *arg in the function?
How to have another argument when we alread have *arg in the function?

Time:04-20

I have a code to add rows of entries using a spinbox. I have the update function to update the changes in the number of rows using the spinbox instantly. Inside this function in the line: for j in range(3): number 3 shows the number of columns of the created entries. So, when we change the number of rows, we have 3 columns.

import tkinter as tk

class Data:
    def __init__(self):
        self.n_para = tk.IntVar()
        self.n_points = tk.IntVar()
        self.seed = tk.IntVar()
        self.n_optional = tk.IntVar()

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.minsize(700, 700)
        container = tk.Frame(self)
        container.pack()

        self.data = Data()

        self.frames = {}
        for F in (PageOne, ):
            frame = F(container, self.data)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

    def show_frame(self, c):
        frame = self.frames[c]
        frame.tkraise()


class PageOne(tk.Frame):
    def __init__(self, parent, data):
        super().__init__(parent)
        self.data = data

        frame1 = tk.Frame(self, width=200)
        frame1.grid(row=0, column=0)

        self.frame2 = tk.Frame(self)
        self.frame2.grid(row=1, column=0)

        frame3 = tk.Frame(self)
        frame3.grid(row=2, column=0)

        label1 = tk.Label(frame1, text="Numeric parameters")
        label1.grid(row=0, column=0, pady=10)

        my_spinbox = tk.Spinbox(frame1, from_=2, to=10, textvariable=data.n_para)
        my_spinbox.grid(row=0, column=1, columnspan=3)

        self.row_list = []
        for i in range(2):
            entry_list1 = []
            for j in range(3):
                entryX = tk.Entry(self.frame2)
                entryX.grid(row=i   1, column=j)
                entry_list1.append(entryX)  # Add entry to list
            self.row_list.append(entry_list1)  # Add entry list to row

        self.data.n_para.trace('w', self.update)  # Trace changes in n_para

    # This function is for updating the number of rows
    def update(self, *args):
        try:
            para = int(self.data.n_para.get())
        except ValueError:
            return  # Return without changes if ValueError occurs

        rows = len(self.row_list)
        diff = para - rows  # Compare old number of rows with entry value

        if diff == 0:
            return  # Return without changes

        elif diff > 0:  # Add rows of entries and remember them
            for row in range(rows   1, rows   diff   1):
                entry_list = []  # Local list for entries on this row
                for col in range(1):
                    e = tk.Entry(self.frame2)
                    e.grid(row=row, column=col)
                    entry_list.append(e)  # Add entry to list
                self.row_list.append(entry_list)  # Add entry list to row

        elif diff < 0:  # Remove rows of entries and forget them
            for row in range(rows - 1, rows - 1   diff, -1):
                for widget in self.row_list[row]:
                    widget.grid_forget()
                    widget.destroy()
                del self.row_list[-1]

app = SampleApp()
app.mainloop()

I wanted to add another argument to update function to get the number of columns. but, I think I have a problem with the concept of *args, and how to add another argument to the function. when I modify the code in the below lines, the code does not work.

def update(self, *args, n_col): 

and

for j in range(n_col):

CodePudding user response:

I think this is a fairly simple solution. (i'm kind of guessing a little to what error your having and how your calling the method) if this is not helpful maybe update the question with the errors.

either reverse the order in which you declare *args and n_col or when calling use a named variable.

def my_sum(*args, ncol):
    result = 0
    # Iterating over the Python args tuple
    for x in args:
        result  = x
    return f"{ncol}   {result}"

print(my_sum(1, 2, 3, ncol=5))

def my_sum(ncol, *args):
    result = 0
    # Iterating over the Python args tuple
    for x in args:
        result  = x
    return f"{ncol}   {result}"

print(my_sum(5, 1, 2, 3))

5   6
5   6

CodePudding user response:

The *args argument must be the last in your method input. Try this:

def update(self, n_col, *args):
  • Related