python 按钮在点击后更改文本
python button change text after click
我想制作一个按钮,在每次点击后更改显示的文本(数字),returns 函数中定义的值,因为我想使用显示的变量。
我创建了一个函数,在每次点击后将 +1 添加到 "text" 直到 4
和一个按钮。该代码没有 return 函数的值,按钮只有文本 = 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
因为 grid()
returns 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()
我想制作一个按钮,在每次点击后更改显示的文本(数字),returns 函数中定义的值,因为我想使用显示的变量。
我创建了一个函数,在每次点击后将 +1 添加到 "text" 直到 4 和一个按钮。该代码没有 return 函数的值,按钮只有文本 = 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
因为 grid()
returns 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()