简体   繁体   English

如何添加带有按钮的新条目字段? 条目字段由 Python Tkinter 中的循环创建

[英]How can I add a new Entry field with a Button? The Entry field was created by a loop in Python Tkinter

在此处输入图像描述

I created entry columns and I want to add new columns by button clicking.我创建了条目列,我想通过单击按钮添加新列。 The problem is I created the columns by a for loop.问题是我通过 for 循环创建了列。 I don't know how I should touch the original loop with the function.我不知道应该如何用 function 触摸原始循环。

My code is looks like this:我的代码是这样的:

list = ['Label1', 'Label2', 'Label3', 'Label4', 'Label5', 'Label6', 'Label7', 'Label8', 'Label9']

def some_def():
    myEntry_loop.grid(row=j, column=k + 1)

for j in range(len(list)):
    for k in range(3):
        myLab = Label(root, text=list[j])
        myLab.grid(row=j, column=0, sticky=E)
        myEntry_loop = Entry(root)
        myEntry_loop.grid(row=j, column=k + 1, pady=10, padx=10)

myButton = Button(root, text="Add New Filed", command=some_def)
myButton.grid(row=10, column=4)

I believe that you would need to define a current value for the y axis.我相信您需要为 y 轴定义一个当前值。 Also, I don't really understand the use of the "list".另外,我不太明白“列表”的用法。 I would recommend to just create ay axis, then just grid the new entry at that y axis.我建议只创建 y 轴,然后在该 y 轴上网格化新条目。

But talking about your current code, the I don't see where you have defined the variable j and k, and you also need to increase k by one each time, not just saying k+1.但是谈到你现在的代码,我没看到你在哪里定义了变量j和k,而且你还需要每次将k加一,而不是只说k+1。

First of all I'd like to highlight you should not use variable name as reserved words like list Now, coming to your requirement.首先,我想强调您不应该使用变量名作为保留字,如list Now,来满足您的要求。 Here's what I wrote这是我写的

li = ['Label1', 'Label2', 'Label3', 'Label4', 'Label5', 'Label6', 'Label7', 'Label8', 'Label9']
from tkinter import *
root = Tk()
col=4
def some_def():
    global col
    for j in range(len(li)):
        myEntry_loop = Entry(root)
        myEntry_loop.grid(row=j, column=col, pady=10, padx=10)
    col+=1
            

for j in range(len(li)):
    myLab = Label(root, text=li[j])
    myLab.grid(row=j, column=0, sticky=E)
    for k in range(3):
        myEntry_loop = Entry(root)
        myEntry_loop.grid(row=j, column=k + 1, pady=10, padx=10)

myButton = Button(root, text="Add New Filed", command=some_def)
myButton.grid(row=10, column=4)

On every button click new column is being created.在每个按钮上单击都会创建新列。 Since you have used the same name of entry widget in your for loop I have used it like that only.由于您在 for 循环中使用了相同名称的条目小部件,因此我只使用了它。 You should know that you wont be able to use methods like get() if you want to extract the content since you have defined all the widgets to be of same name.您应该知道,如果您想提取内容,您将无法使用 get() 之类的方法,因为您已将所有小部件定义为同名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM