如何在str中保存条目计数器并在文本字段中显示?

2024-04-16 07:06:10 发布

您现在位置:Python中文网/ 问答频道 /正文

使用这样的例子,我想计算条目数。并用文本字段中的条目数表示字符串。例如:

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()

Tags: textselfnumberdef条目columnrootmyapp
2条回答

你好像在用Python3。你知道吗

存储计数器的最简单方法是使用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()

如果我正确地理解了您想要什么,只需保持按钮按下次数的计数,就可以在__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))

相关问题 更多 >