使用这样的例子我想计算条目数。并在“文本”字段中表示具有条目数的字符串。比如,例如:
1: number of entries(1)
21: number of entries(2)
...
我应该把我的计数器变量放在哪里?
import random
from tkinter import *
class MyApp(Frame):
def __init__(self, master):
super(MyApp, self).__init__(master)
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):
guess = self.num_ent.get()
guess += '\n'
self.user_text.insert(0.0, guess)
root = Tk()
root.geometry('410x200')
root.title('Entries counter')
app = MyApp(root)
root.mainloop()
答案 0 :(得分:0)
看来你正在使用Python 3。
存储计数器的最简单方法是使用dictionary。关键是您正在计算的文本(根据您的示例为1和21),该值存储计数本身(例如1和2)。
您示例的结构化数据如下所示:
{
'1': 1,
'21': 2
}
最后的代码:
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()
答案 1 :(得分:0)
如果我理解你想要的东西,只需记下按钮数量,你可以在__init__
中定义一个计数变量,如
self.count = 0
并在update
中增加并打印
def update(self):
self.count += 1
guess = self.num_ent.get()
guess += '\n'
self.user_text.insert(0.0, 'Guess #{}: {}'.format(self.count, guess))