如何为tkinter中创建的按钮被按下的次数创建计数器



所以我制作了一个简单的程序,允许我为按钮键入标签,并在tkinter-gui中创建和点击它。现在我只需要添加一个函数,返回每个按钮的点击次数。问题是,我创建的按钮实际上并没有在输入中编码,所以我发现很难做到这一点。我觉得我必须使用lambda函数,但我根本没有使用它的经验。非常感谢您的帮助,谢谢。

代码:

import tkinter as tk
from tkinter import *
window = tk.Tk()
window.title("Tkinter FINAL")
window.geometry("600x400")
window.resizable(width=False, height=False)
WIDTH = 800
HEIGHT = 600
counter_name = tk.Label(window, text="Counter Word", width=20)
counter_name.place(x=460,y=318)
counter_entry = tk.Entry(window, width=20)
counter_entry.place(x=470,y=338)
position_x = 0
position_y = 0

word_dict = {}
def button_function():
word_dict[title] += 1
button_count = 0
def button_maker():
global position_x, position_y, button_count, title
button = tk.Button(window, text=counter_entry.get(), width=10, height=2, command = button_function, fg="red")
button.place(x=position_x,y=position_y)
position_x += 116
button_count += 1
if button_count % 6 == 0:
position_y += 50
position_x = 0
title = counter_entry.get()
word_dict[title] = 0
counter_entry.delete(0,'end')


btnmaker = tk.Button(window, text='Click to create counter', width=17, height=2, command = button_maker, fg="red")
btnmaker.place(x=470,y=358)

btnreset = tk.Button(window, text='RESET', width=10, height=2, command = window.destroy, fg="red")
btnreset.place(x=520,y=500)
window.mainloop()

您需要使用lambda:将输入的单词传递给button_function()

word_dict = {}
def button_function(word):
word_dict[word] += 1
print(word, word_dict[word])
def button_maker():
# get the input word
word = counter_entry.get().strip()
# make sure the input word is unique in the dictionary
if word and word not in word_dict:
count = len(word_dict)
button = tk.Button(window, text=word, width=10, height=2, fg="red",
command=lambda w=word: button_function(w)) # pass the input word to button_function()
button.place(x=count%5*116, y=count//5*60)
word_dict[word] = 0  # init the counter for the input word
counter_entry.delete(0,'end')

带有计数器标签的更新代码:

word_dict = {}
def button_function(word):
count = word_dict[word].get()
word_dict[word].set(count+1)
def button_maker():
word = counter_entry.get().strip()
if word and word not in word_dict:
count = len(word_dict)
row, col = count//5*2, count%5
# create the word button
button = tk.Button(window, text=word, width=10, height=2, fg="red",
command=lambda w=word: button_function(w))
button.grid(row=row, column=col, padx=10, pady=(10,0))
# create the corresponding counter label        
var = tk.IntVar() # for the counter value
tk.Label(window, textvariable=var).grid(row=row+1, column=col)
word_dict[word] = var
counter_entry.delete(0, 'end')

最新更新