我需要实现这个功能:当在空格填入任何内容后,自动把空格的内容更新到一个字典里。
我用面向编程思路编写,运行正常,达到我的目的。
from tkinter import *
from tkinter.ttk import *
root = Tk()
name = '张三'
age = '40'
record = {'姓名': name, '年龄': age}
def refresh_name(self, *args):
'''
更新字典里的名字
'''
record['姓名'] = content_name.get()
print(record)
def refresh_age(self, *args):
'''
更新字典里的年龄
'''
record['年龄'] = content_age.get()
print(record)
Label(root, text='姓名').grid(pady=10, row = 1, column = 1, sticky = E)
content_name = StringVar()
content_name.set(record['姓名'])
content_name_blk = Entry(root, textvariable = content_name, width = 10)
content_name_blk.grid(pady=10, row = 1, column = 2, sticky = W)
content_name_blk.bind('<KeyRelease>', refresh_name)
Label(root, text='年龄').grid(pady=10, row = 1, column = 3, sticky = E)
content_age = StringVar()
content_age.set(record['年龄'])
content_age_blk = Entry(root, textvariable = content_age, width = 10)
content_age_blk.grid(pady=10, row = 1, column = 4, sticky = W)
content_age_blk.bind('<KeyRelease>', refresh_age)
root.mainloop()
但是当我用面向对象思路编写后,2个空格的内容居然同步了,而且当我在其中一个空格填写时,另外一个空格也跟着一起刷新相同的内容。
from tkinter import *
from tkinter.ttk import *
root = Tk()
name = '张三'
age = '40'
record = {'姓名': name, '年龄': age}
class Blank:
'''
新建填空类,由标签和空格2部分组成。功能:每输入一个字,自动更新record字典。
'''
def __init__(self, name, row, column, content = StringVar()):
self.name = name
self.row = row
self.column = column
Label(root, text=self.name).grid(pady=10, row = self.row, column = self.column, sticky = E)
self.content = content
self.content.set(record[self.name])
a = Entry(root, textvariable = self.content, width = 10)
a.grid(pady=10, row = self.row, column = self.column + 1, sticky = W)
a.bind('<KeyRelease>', self.refresh)
def refresh(self, *args):
'''
更新字典
'''
record[self.name] = self.content.get()
print(record)
name_blk = Blank('姓名', 1, 1)
age_blk = Blank('年龄', 1, 3)
root.mainloop()
Blank类生成的对象应该是独立的,为什么空格显示的内容会同步,而字典里却又按照各自的不同变量显示呢?