python - 从 Entry 获取信息

标签 python python-3.x oop tkinter

我的名字是罗德。我最近开始使用 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/

相关文章:

javascript - 是否可以在 chrome 中运行 native python 代码?

python - 如何使用 Dataflow 在 apache beam 中跳过 io 级别的错误元素?

python - Pandas 将新列名分配为字符串

python - 为什么 Pycharm 打印比写入文件少?

python - 相似类型对象之间的类型转换设计

python-3.x - 如何从python3中的同级目录导入?

在全局声明之前使用的 Python 3 SyntaxWarning 变量

python-3.x - 每个超参数的 Hyperopt 值列表

javascript - JavaScript 中的属性初始化

C++ 重载函数和子类