Tkinter:使用Button实例化对象

时间:2013-12-31 02:52:19

标签: python python-3.x tkinter

我正在使用Python 3.3中的tkinter搞乱,并且想知道如何使用/创建带有按钮的对象。我有以下代码:

from tkinter import *

class Person:
    def __init__(self, name, age, title):
        self.name = name
        self.age = age
        self.title = title

    def print_person(self):
        return self.name, str(self.age), self.title


def hello(lbl, nm):
    lbl.config(text="Hello, " + nm)


root = Tk()
frame = Frame(root)

name_lbl = Label(root, text="Name: ").grid()
name_ent = Entry(root)
name_ent.grid(row=0, column=1)

age_lbl = Label(root, text="Age: ").grid(row=1, column=0)
age_ent = Entry(root)
age_ent.grid(row=1, column=1)

title_lbl = Label(root, text="Title: ").grid(row=2, column=0)
title_ent = Entry(root)
title_ent.grid(row=2, column=1)

hello_lbl = Label(root, text="").grid(row=4, columnspan=2)
btn = Button(root, text="Confirm", command=lambda: Person(name_ent.get(), age_ent.get(), title_ent.get())).grid(row=3, columnspan=2)



root.mainloop()

如何通过单击按钮为以后创建的对象命名?例如,如何通过填写条目并单击按钮来对创建的对象使用print_person()方法?

1 个答案:

答案 0 :(得分:1)

使用变量保存Person对象。

例如:

...
def create_a_person():
    global person
    person = Person(name_ent.get(), age_ent.get(), title_ent.get())

Button(root, text="Confirm", command=create_a_person).grid(row=3, columnspan=2)
Button(root, text="Print", command=lambda: print(person.print_person())).grid(row=4, columnspan=2)
...

BTW,grid方法返回None

hello_lbl = Label(root, text="").grid(row=4, columnspan=2) # => None

如果您希望保存Label,则应使用以下格式:

hello_lbl = Label(root, text="")
hello_lbl.grid(row=4, columnspan=2)