You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在点击按钮后将tkinter计数器重置为0?

Add Reset Functionality to Tkinter Counter

First, let's fix a small typo in your original code: you defined the increment function as OnClick (capital O), but the button's command uses onClick (lowercase o) — that'll throw a NameError if you run it. Let's fix that first, then add the reset feature you need.

Here's how to implement the reset functionality step by step:

  • Create a dedicated function that sets the counter variable back to 0
  • Add a second button that triggers this function when clicked

Full Modified Code

import tkinter
import sys

root = tkinter.Tk()
root.geometry("200x200")
root.title("His Button Increaser")

counter = tkinter.IntVar()

def OnClick(event=None):
    counter.set(counter.get() + 1)

# New function to reset counter to 0
def resetCounter():
    counter.set(0)

tkinter.Label(root, textvariable=counter).pack(pady=10)
tkinter.Button(root, text="One up", command=OnClick).pack(pady=5)
# New reset button linked to the reset function
tkinter.Button(root, text="Reset to 0", command=resetCounter).pack(pady=5)

root.mainloop()

Key Changes Explained

  1. Fixed function name mismatch: The button's command now correctly references OnClick (matches the function definition) to avoid runtime errors
  2. Added resetCounter() function: This straightforward function updates the counter IntVar directly to 0
  3. Added the reset button: A new button labeled "Reset to 0" is added below the increment button, with small padding to keep the UI clean and spaced out

Run this code, and you'll be able to increment the counter with "One up" and reset it to 0 anytime using the new button!

内容的提问来源于stack exchange,提问作者Stavrius Mtvs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:10:22