当我们在函数中使用 *arg时,如何有另一个参数?

发布于 2025-01-22 15:39:36 字数 3243 浏览 0 评论 0原文

我有一个代码可以使用spinbox添加行条目。我有Update功能,可以立即使用Spinbox更新行数的更改。在该行中的此功能内部:范围(3)中的J <代码>:数字3显示了创建条目的列数。因此,当我们更改行数时,我们有3列。

import tkinter as tk


class Data:
    def __init__(self):
        self.n_para = 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.update1)  # Trace changes in n_para

    # This function is for updating the number of rows
    def update1(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()

我想将另一个参数添加到update1函数以获取列数。但是,我认为我对*args的概念有问题,以及如何向功能添加另一个参数。 当我在以下行中修改代码时,代码不起作用。

def update1(self, *args, n_col): 

for j in range(n_col):

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()


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.update1)  # Trace changes in n_para

    # This function is for updating the number of rows
    def update1(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 update1 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 update1(self, *args, n_col): 

and

for j in range(n_col):

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

三岁铭 2025-01-29 15:39:36

我认为这是一个相当简单的解决方案。 (我有点猜测您的错误以及您如何调用方法),如果这无用,则可以使用错误更新问题。

要么扭转您声明 *args和n_col的顺序,要么在调用时使用命名变量。

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

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
浮生面具三千个 2025-01-29 15:39:36

*args参数必须是您的方法输入中的最后一个。
尝试以下操作:

def update(self, n_col, *args):

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

def update(self, n_col, *args):
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文