python按钮点击后更改文本

标签 python button tkinter widget

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

我创建了一个函数,每次点击后都会为“文本”添加 +1,直到 4 和一个按钮。该代码不返回函数的值,按钮只有文本 = 1、2、3 或 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(..)

分配Nonebtn因为grid()返回None

使用

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

现在您可以使用 btn['text'] = "new text" 更改按钮上的文本或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按钮点击后更改文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33939869/

相关文章:

python - windows 认为 tkinter 没有响应

python - Web2Py SQLFORM.Grid

python - 在 matplotlib 的图例框中更改标记的大小/alpha

python - 将 C++ 抽象类作为参数传递给 Cython

c# - 将保存按钮绑定(bind)到 DataTable

iOS编程: customized buttons in viewDidAppear

python - Tkinter动态 "iframe"不会滚动

python - PyGreSQL 与 psycopg2

html - 如何制作单击时播放音频的图像

python - 如何在 Tkinter 应用程序中启用对表情符号的支持?