简体   繁体   English

在Python 3中使用tkinter时,如何在每次按下函数时获得一个按钮来运行函数?

[英]When using tkinter in Python 3, how do you get a button to run a function each time it is pressed?

import tkinter as tk
panel = tk.Tk()
num = 42
lbl1 = tk.Label(panel, text = str(num))

Let's say I have a function and button like this: 假设我有一个像这样的功能和按钮:

def increase():
    lbl1.configure(text = str(num+1))

btn = tk.Button(panel, text = 'Increase', command = increase)

panel.mainloop()

This button will make the number that is the label increase by 1 when pressing the button. 按下按钮时,标签上的数字将增加1。 However, this only works once before the button does absolutely nothing. 但是,此操作仅在按钮完全不起作用之前起作用一次。 How can I make it so that every time I press the button, the number increases by 1? 如何使每次按下按钮时数字增加1?

You never saved the incremented value of num . 您从未保存过num的增量值。

def increase():
    global num # declare it a global so we can modify it
    num += 1 # modify it
    lbl1.configure(text = str(num)) # use it

It's because num is always 43 因为num总是43

import tkinter as tk
num = 42

def increase():
    global num
    num += 1
    lbl1.configure(text = str(num))


panel = tk.Tk()

lbl1 = tk.Label(panel, text = str(num))
lbl1.pack()
btn = tk.Button(panel, text = 'Increase', command = increase)
btn.pack()
panel.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 每次在“tkinter”中按下按钮时,如何为标签获取不同的值? - How do you get a different value for a label each time a button is pressed in `tkinter`? 您如何在python tkinter中说“如果按下按钮,然后执行此操作”? - How do you say “If button is pressed, then do this” in python tkinter? 在 Python 中按下按钮(tkinter)时如何执行另一个文件? - How do you execute another file when a button is pressed(tkinter) in Python? python tkinter如果没有按下按钮运行功能 - python tkinter if no button pressed run function 按下Tkinter按钮时,Python运行脚本 - Python run script when Tkinter button pressed python) 当按下按钮时,如何使 tkinter 出现? - python) How do I make tkinter appear when a button is pressed? 按下时从Python 2 Tkinter按钮运行函数,然后在释放时运行另一个函数 - Run function from Python 2 Tkinter button when pressed then run another when released 如何在tkinter中按下按钮时调用函数? - How to call a function when a button is pressed in tkinter? 按下按钮后,如何在python中获取按钮以运行python代码? - How do I get a button in python to run a python code when pressed? 每次在 tkinter 中按下按钮时,如何创建一个将列增加 1 的函数? - How do I make a function that increases the column by 1 every time a button is pressed in tkinter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM