【问题标题】:python button change text after click单击后python按钮更改文本
【发布时间】:2016-02-29 14:55:40
【问题描述】:

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

我创建了一个函数,在每次点击后向“文本”添加 +1 直到 4 和一个按钮。代码不返回函数的值,按钮只有 text = 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(..) 总是将None 分配给btn。使用使用btn = tk.Button(...) ; btn.grid(...)

标签: python button tkinter widget


【解决方案1】:

第一个

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

None 分配给btn,因为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()

【讨论】:

  • 谢谢!您知道如何将 1、2、3 或 4 分配给变量吗?所以我可以使用变量
  • 我不明白你的意思。你已经有了 text 变量,你可以使用它。
  • 是的,但我认为“text_change()”中的文本值是本地的,所以文本 = 0 总是 0。我想用“text_change”的文本值覆盖文本 = 0 ()"
  • 以我的代码为例:a = text if a == 1: print("kkk") 不起作用
  • text 不是本地的,因为我使用了global text
猜你喜欢
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-02
  • 1970-01-01
  • 2022-01-19
相关资源
最近更新 更多