简体   繁体   中英

How to add a new entry box when clicking a button (Python, Tkinter)

Hi i want to add a new entry box when clicking a button. How can i do that? What've done is im able to "for loop" a group of entry boxes. But i want the entry boxes to appear one by one by clicking a button.

What've done

在此处输入图像描述

My code:

import tkinter as tk
from tkinter import *

root = Tk()
root.title("Entry box")
root.geometry("700x500")

my_entries = []

def something():

    entry_list = ''
    for entries in my_entries:
        entry_list = entry_list + str(entries.get()) + '\n'
        my_label.config(text=entry_list)
    print(my_entries[0].get())

for x in range(5):
    my_entry = Entry(root)
    my_entry.grid(row=0, column=x, pady=20, padx=5)
    my_entries.append(my_entry)

my_button = Button(root, text="Click Me!", command=something)
my_button.grid(row=1, column=0, pady=20)


There is not much of work here, create a variable to keep track of the columns you are inserting the widget into and then just insert it based on that number, like:

# Rest of your code..

my_entries = []
count = 0 # To keep track of inserted entries
def add():
    global count
    MAX_NUM = 4 # Maximum number of entries
    if count <= MAX_NUM:
        my_entries.append(Entry(root)) # Create and append to list
        my_entries[-1].grid(row=0,column=count,padx=5) # Place the just created widget
        count += 1 # Increase the count by 1

Button(root, text='Add', command=add).grid(row=1, column=1, padx=10) # A button to call the function
# Rest of your code..

Though I am not sure about your other function and its functionality, but it should work after you create entries and then click that button.

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