如何在按钮功能中传递Entry
的值?
我想将值传递给函数onConfirm()
from tkinter import Tk, ttk, Frame, Button, Label, Entry, Text, Checkbutton, \
Scale, Listbox, Menu, BOTH, RIGHT, RAISED, N, E, S, W, \
HORIZONTAL, END, FALSE, IntVar, StringVar, messagebox as box
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="skyblue")
self.parent = parent
self.parent.title("Simple Window")
self.style = ttk.Style()
self.style.theme_use("default")
self.centreWindow()
self.pack(fill=BOTH, expand=1)
firstNameLabel = Label(self, text="First Name")
firstNameLabel.grid(row=0, column=0, padx=(100,10), pady=(100,10))
firstNameText = Entry(self, width=20)
firstNameText.grid(row=0, column=1, pady=(100,10))
okBtn = Button(self, text="OK", width=10, command= lambda: self.onConfirm(firstNameText.get()))
okBtn.grid(row=0, column=2,padx = 5, pady=(100,10))
# closeBtn = Button(self, text="Close", width=10, command=self.onExit)
#closeBtn.grid(row=4, column=3, padx=5, pady=3, sticky=W+E)
def centreWindow(self):
w = 500
h = 300
sw = self.parent.winfo_screenwidth()
sh = self.parent.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
def onConfirm(self,s):
box.showinfo("Information", s)
def main():
root = Tk()
#root.geometry("250x150+300+300") # width x height + x + y
# we will use centreWindow instead
root.resizable(width=FALSE, height=FALSE)
# .. not resizable
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
答案 0 :(得分:0)
您不必传递变量,因为您正在使用类。尝试改为
## instance object can be used throughout the class
self.firstNameText = Entry(self, width=20)
self.firstNameText.grid(row=0, column=1, pady=(100,10))
## Button just calls function
okBtn = Button(self, text="OK", width=10, command=self.onConfirm)
okBtn.grid(row=0, column=2,padx = 5, pady=(100,10))
## function has access to instance variable
def onConfirm(self):
s=self.firstNameText.get()
box.showinfo("Information", s)