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.

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()

I hope you can help me :)

解决方案

First

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

assigns None to btn because grid() returns None

use

btn = tk.Button(...)

btn.grid(...)

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值