简体   繁体   中英

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. I don't know how I should touch the original loop with the 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. 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.

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.

First of all I'd like to highlight you should not use variable name as reserved words like list Now, coming to your requirement. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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