从入口获取信息

2024-04-20 08:54:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我叫罗德。我最近开始用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()

Tags: textfromimportselfappapplicationinittkinter
1条回答
网友
1楼 · 发布于 2024-04-20 08:54:47

每次创建条目时,都会覆盖前面的值text。所有以前的输入框现在都是孤立的:无法访问它们来获取信息(因为它们是局部变量,所以无论如何都无法访问)

相反,您可以将新的StringVars添加到一个容器中,比如一个列表,这样您就可以访问所有的StringVars

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()

相关问题 更多 >