我的名字是罗德。我最近开始使用 OOP 进行编程,但我还不太清楚。我想让我的按钮从我的四个条目中获取信息,但我不知道如何对程序说以同时从四个条目中获取信息。我知道我必须使用 get() 方法,但我不明白如何将其插入类中,以便它能够识别我的四个条目。谢谢!
from tkinter import *
from tkinter import ttk
class Application(Frame):
def __init__(self):
Frame.__init__(self)
self.grid()
def createButton(self,b_text,b_command,r,c):
self.newButton = Button(self, text=b_text,command=b_command)
self.newButton.grid(padx=20, pady=10, row=r,column=c)
def createEntry(self,px,r,c):
text = StringVar()
self.newEntry = Entry(self,width=8,textvariable=text)
self.newEntry.grid(padx=px, pady=10,row=r,column=c)
def printEntryData():
#code here
app = Application()
entry1 = app.createEntry(20,0,0)
entry2 = app.createEntry(20,0,1)
entry3 = app.createEntry(20,0,2)
entry4 = app.createEntry(20,0,3)
app.createButton("add",printEntryData,1,6)
app.mainloop()
最佳答案
每次输入内容时,都会覆盖 text
的先前值。所有以前的输入框现在都是孤立的:无法访问它们来获取信息。 (无论如何它们都是不可访问的,因为它们是局部变量)。
相反,您可以将新的 StringVar 添加到列表等容器中,以便您可以访问所有它们。
from tkinter import *
from tkinter import ttk
class Application(Frame):
def __init__(self):
Frame.__init__(self)
self.entry_list = []
self.grid()
def createButton(self,b_text,b_command,r,c):
self.newButton = Button(self, text=b_text,command=b_command)
self.newButton.grid(padx=20, pady=10, row=r,column=c)
def createEntry(self,px,r,c):
text = StringVar()
self.newEntry = Entry(self,width=8,textvariable=text)
self.newEntry.grid(padx=px, pady=10,row=r,column=c)
self.entry_list.append(text)
def printEntryData():
for entry in app.entry_list:
print(entry.get())
app = Application()
app.createEntry(20,0,0)
app.createEntry(20,0,1)
app.createEntry(20,0,2)
app.createEntry(20,0,3)
app.createButton("add",printEntryData,1,6)
app.mainloop()
关于python - 从 Entry 获取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48176353/