单击后python按钮更改文本

python button change text after click(单击后python按钮更改文本)
本文介绍了单击后python按钮更改文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个按钮,在每次点击后更改显示的文本(数字)并返回函数中定义的值,因为我想使用显示的变量.

i want to make a Button that changes the displayed text(number) after every click and returns the valure defined in the function, because i want to work with the displayed variables.

我创建了一个函数,在每次点击后向文本"添加 +1 直到 4和一个按钮.代码不返回函数的值,按钮只有 text = 1,2,3 或 4.

I created a function that adds +1 to "text" after every click until 4 and a button. The code does not return the valure of the function and the button has only the text = 1,2,3 or 4.

import tkinter as tk

root = tk.Tk()

text = 0
def text_change():
    global text
    text += 1

    print(text)
    if text >= 4:
        text = 0

#to change: button text has to be the variable defined in the function
btn = tk.Button(text = "1,2,3 or 4", width = 10, height = 3, command = 
                text_change).grid(row = 1 , column = 1)

root.mainloop()

我希望你能帮助我:)

推荐答案

首先

btn = tk.Button(...).grid(..)

None 分配给 btn 因为 grid() 返回 None

assigns None to btn because grid() returns None

使用

btn = tk.Button(...)
btn.grid(...)

现在您可以使用 btn['text'] = "new text"btn.config(text="new text")

Now you can change text on button using btn['text'] = "new text" or btn.config(text="new text")

import tkinter as tk

# --- functions ---

def text_change():
    global text

    text += 1

    if text > 4:
        text = 1

    print("changed to:", text)

    #btn['text'] = text
    btn.config(text=text)

def text_print():
    print("current:", text)

# --- main ---

text = 0

root = tk.Tk()

btn = tk.Button(text="1,2,3 or 4", command=text_change, width=10, height=3)
btn.grid(row=1, column=1)

btn2 = tk.Button(text="SHOW", command=text_print, width=10, height=3)
btn2.grid(row=2, column=1)

root.mainloop()

这篇关于单击后python按钮更改文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)