[英]How do I make a button in tkinter that allows me to count the number of times it has been pressed?
I've been trying to create a button in tkinter that tracks the amount of times hat it has been clicked but it shows me a syntax error every time I click it.我一直在尝试在 tkinter 中创建一个按钮来跟踪它被点击的次数,但每次我点击它都会显示一个语法错误。
The way I intend it to work is for it to add one to the counter every time the top button is clicked, and then upon clicking the bottom one, the programme will close and the amount of times the top button has been clicked will be printed.我打算它的工作方式是每次单击顶部按钮时向计数器添加一个,然后单击底部按钮时,程序将关闭并打印顶部按钮被单击的次数.
from tkinter import *
count = 0
def counter():
count = count + 1
def total():
print(count)
exit ()
window = Tk()
window.geometry("175x105")
window.resizable(0, 0)
text=Label(window, text="Click the button.", font=("Times New Roman", 10))
text.pack(padx=3, pady=3)
button=Button(window, text="CLICK HERE", width=12, bg="gray", command=counter)
button.pack(padx=2, pady=2)
button2=Button(window, text="FINISH", width=12, bg="gray", command=total)
button2.pack(padx=2, pady=2)
window.mainloop()
You only have to globalize the variable count
inside the counter()
function.您只需要将
counter()
函数中的变量count
全球化。 It will update the value of count every time the function is called.每次调用该函数时,它都会更新 count 的值。
Like this:像这样:
import tkinter as tk
count = 0
def counter():
global count
count = count + 1 # you can also use: count += 1
def total():
print(count)
exit()
window = tk.Tk()
window.geometry("175x105")
window.resizable(0, 0)
text = tk.Label(window, text="Click the button.", font=("Times New Roman", 10))
text.pack(padx=3, pady=3)
button = tk.Button(window, text="CLICK HERE", width=12, bg="gray", command=counter)
button.pack(padx=2, pady=2)
button2 = tk.Button(window, text="FINISH", width=12, bg="gray", command=total)
button2.pack(padx=2, pady=2)
window.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.