<p>你好像在用Python3。你知道吗</p>
<p>存储计数器的最简单方法是使用<a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a>。关键是您正在计数的文本(根据您的示例为1和21),该值存储计数本身(例如1和2)。你知道吗</p>
<p>示例中的结构化数据如下所示:</p>
<pre class="lang-python prettyprint-override"><code>{
'1': 1,
'21': 2
}
</code></pre>
<p>最后的代码是:</p>
<pre class="lang-python prettyprint-override"><code>from tkinter import *
class MyApp(Frame):
def __init__(self, master):
super(MyApp, self).__init__(master)
#this is your counter variable
self.entries = {}
self.grid()
self.create_widgets()
def create_widgets(self):
Label(self, text = 'Your number:').grid(row = 0, column = 0, sticky = W)
self.num_ent = Entry(self)
self.num_ent.grid(row = 0, column = 1, sticky = W)
Button(self, text = 'Check', command = self.update).grid(row = 0, column = 2, sticky = W)
self.user_text = Text(self, width = 50, height = 40, wrap = WORD)
self.user_text.grid(row = 2, column = 0, columnspan = 3)
def update(self):
#get the new entry from the text field and strip whitespaces
new_entry = self.num_ent.get().strip()
#check if the entry is already in the counter variable
if new_entry in self.entries:
#if it is: increment the counter
self.entries[new_entry] += 1
else:
#if it's not: add it and set its counter to 1
self.entries[new_entry] = 1
#delete the whole text area
self.user_text.delete('0.0', END)
#get every entry from the counter variable, sorted alphabetically
for key in sorted(self.entries):
#insert the entry at the end of the text area
self.user_text.insert(END, '{}: number of entries({})\n'.format(key, self.entries[key]))
root = Tk()
root.geometry('410x200')
root.title('Entries counter')
app = MyApp(root)
root.mainloop()
</code></pre>