如何在Python Tkinter中创建按钮以将整数变量增加1并显示该变量? [英] How do I create a button in Python Tkinter to increase integer variable by 1 and display that variable?

查看:71
本文介绍了如何在Python Tkinter中创建按钮以将整数变量增加1并显示该变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Tkinter程序,该程序将存储一个int变量,并在每次单击按钮时将该int变量增加1,然后显示该变量,以便可以看到它以0开始,然后每次我单击按钮时,它都会增加1.我使用的是python 3.4.

I am trying to create a Tkinter program that will store an int variable, and increase that int variable by 1 each time I click a button, and then display the variable so I can see that it starts out as 0, and then each time I click the button it goes up by 1. I am using python 3.4.

import sys
import math
from tkinter import *

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

counter = 0
def nClick():
    counter + 1

def main_click():
    mLabel = Label(root, text = nClick).pack()


mButton1 = Button(text = "Increase", command = main_click, fg = "dark green", bg = "white").pack()

root.mainloop()

推荐答案

好,到目前为止,您的代码有些错误.我的回答基本上将您已经拥有的东西变成了最简单的方式来完成您想要的事情.

Ok so there are a few things wrong with your code so far. My answer basically changes what you have already into the easiest way for it to do what you want.

首先,导入不需要/不使用的库(您可能在整个代码中都需要它们,但是对于此问题,仅包括一个最小的示例).接下来,您必须将 counter 变量定义为 global 变量,以使其在函数中相同(也可以在函数内部执行此操作).另外,您还必须将 counter + 1 更改为 counter + = 1 ,以使变量递增

Firstly you import libraries that you don't need/use (you may need them in your whole code, but for this question include a minimal example only). Next you must deifne the counter variable as a global variable, so that it will be the same in the function (do this inside the function as well). Also you must change counter + 1 to counter += 1 so it increments the variable

现在该代码将可以计数,但是您已将变量设置为Buttons,然后将它们设置为None类型对象,以在下一行更改此 .pack()变量.您只需第二个功能就可以摆脱它,然后将按钮的命令及其文本更改为counter.现在,要更新按钮中的文本,请使用配置按钮的 .config(text = counter).

Now the code will be able to count, but you have set variables as Buttons, but then made them None type objects, to change this .pack() the variable on the next line. You can get rid of the second function as you only need one, then you change the command of the button and its text to counter. Now to update the text in the button, you use .config(text = counter) which configures the button.

这是最终的解决方案(更改按钮值并且没有标签,但这很容易更改):

Here is the final solution (changes button value and has no label, but this is easily changed):

from tkinter import *

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

global counter
counter = 0

def nClick():
    global counter
    counter += 1
    mButton1.config(text = counter)

mButton1 = Button(text = counter, command = nClick, fg = "darkgreen", bg = "white")
mButton1.pack()

root.mainloop()

希望有帮助!

这篇关于如何在Python Tkinter中创建按钮以将整数变量增加1并显示该变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆