Python tkinter中的新输入字段

时间:2019-05-18 11:59:43

标签: python tkinter

我一直在尝试使用tkinter创建一个python程序,在其中您可以通过按一个按钮添加两个字段。然后,在按下按钮后,代码将采用两个字段并将它们放在变量中。它还具有两个标题,这些标题根据其所在的数字字段而动态更改,并且每次都位于其下方。

我将如何创建执行此操作的按钮。到目前为止,我在输入字段中的代码是:

from tkinter import * #Import the Tkinter module
from tkinter import messagebox #Imports the message box module
from tkinter import font #Imports fonts from tkinter

count = 2

master = Tk() #Tkinter

Label(master, text="Title", font=("Helvetica", 20, "bold underline")).grid(row=0) 
Label(master, text="Subtitle 1", font=("Helvetica", 17, "bold underline")).grid(row=2) 
Label(master, text="Entry Title 1a").grid(row=3)
Label(master, text="Entry Title 1b").grid(row=4)

entry1 = Entry(master) #Entry Fields
entry2 = Entry(master)
entry1.grid(row=3, column=1) #Puts Entry fields in a certain location
entry2.grid(row=4, column=1) # ^


Label(master, text="Subtitle 2", font=("Helvetica", 17, "bold underline")).grid(row=5)
Label(master, text="Entry title 2a").grid(row=6)
q1=Label(master, text="Entry title 2b").grid(row=7)
entry3 = Entry(master) #Entry Fields
entry4 = Entry(master)

entry3.grid(row=6, column=1)
entry4.grid(row=7, column=1)

谢谢!

1 个答案:

答案 0 :(得分:0)

据我所知,您想知道如何使用“输入”字段中的值进行计算。

执行此操作的方法是使用.get()函数。例如entry1.get()来获取在entry1字段中输入的值。

我使用您的代码创建了执行此操作的示例:

(编辑)我更改了按钮的功能以创建新的输入字段,要访问这些输入字段,我将输入字段添加到了列表中,您可以从该列表中访问这些条目。

from tkinter import * #Import the Tkinter module
from tkinter import messagebox #Imports the message box module
from tkinter import font #Imports fonts from tkinter

count = 2

master = Tk() #Tkinter

Label(master, text="Title", font=("Helvetica", 20, "bold underline")).grid(row=0)
Label(master, text="Subtitle 1", font=("Helvetica", 17, "bold underline")).grid(row=2)
Label(master, text="Entry Title 1a").grid(row=3)
Label(master, text="Entry Title 1b").grid(row=4)

entry1 = Entry(master) #Entry Fields
entry2 = Entry(master)
entry1.grid(row=3, column=1) #Puts Entry fields in a certain location
entry2.grid(row=4, column=1) # ^


Label(master, text="Subtitle 2", font=("Helvetica", 17, "bold underline")).grid(row=5)
Label(master, text="Entry title 2a").grid(row=6)
q1=Label(master, text="Entry title 2b").grid(row=7)
entry3 = Entry(master) #Entry Fields
entry4 = Entry(master)

entry3.grid(row=6, column=1)
entry4.grid(row=7, column=1)

button1 = Button(master, text="Button 1", bg="snow", command=lambda: create_entry())
button1.grid(row=8, column=0, columnspan=2)

global row_count, entries
row_count = 9
entries = []


def create_entry():
    global row_count, entries
    temp_entry = Entry(master)
    temp_entry.grid(row=row_count, column=1)
    entries.append(temp_entry)
    Label(master, text="Entry title " + str(row_count)).grid(row=row_count)
    row_count += 1

def entries_multiplied():
    value = 1
    global entries
    for entry in entries:
        value *= int(entry.get()) if entry.get() != "" else 1
    return value


master.mainloop()