Python 3,Tkinter,如何更新按钮文本

10

我正在尝试让用户单击按钮时,它会变成“X”或“0”(取决于他们所在的团队)。如何使按钮上的文本更新?到目前为止,我最好的想法是删除按钮,然后再次打印它们,但这只能删除一个按钮。以下是我的代码:

from tkinter import *

BoardValue = ["-","-","-","-","-","-","-","-","-"]

window = Tk()
window.title("Noughts And Crosses")
window.geometry("10x200")

v = StringVar()
Label(window, textvariable=v,pady=10).pack()
v.set("Noughts And Crosses")

def DrawBoard():
    for i, b in enumerate(BoardValue):
        global btn
        if i%3 == 0:
            row_frame = Frame(window)
            row_frame.pack(side="top")
        btn = Button(row_frame, text=b, relief=GROOVE, width=2, command = lambda: PlayMove())
        btn.pack(side="left")

def PlayMove():
    BoardValue[0] = "X"
    btn.destroy()
    DrawBoard()

DrawBoard()
window.mainloop()
7个回答

32

总之,在这个主题中:button.configbutton.configure都可以正常工作!

button.config(text="hello")
或者
button.configure(text="hello")

15

Button小部件和Label一样,也有textvariable=选项。您可以使用StringVar.set()来更新Button。最简示例:

import tkinter as tk

root = tk.Tk()

def update_btn_text():
    btn_text.set("b")

btn_text = tk.StringVar()
btn = tk.Button(root, textvariable=btn_text, command=update_btn_text)
btn_text.set("a")

btn.pack()

root.mainloop()

1
如何使得被点击的按钮是发生变化的那一个,而不是像现在一样只更新最后一个按钮。 - Mrchooch
1
@Mrchooch 每个按钮都需要一个单独的 tk.StringVar。请参考 http://effbot.org/tkinterbook/variable.htm。 - David
2
您也可以直接调用按钮的configure方法,而无需使用StringVar。虽然使用StringVar是可行的,但这会增加一个要维护的额外对象,而没有提供任何额外的好处。 - Bryan Oakley

5

btn只是一个包含数值的字典,让我们看看它包含了哪些内容:

#lets do another button example
Search_button
<tkinter.Button object .!button>
#hmm, lets do dict(Search_button)
dict(Search_button)
{'activebackground': 'SystemButtonFace', 'activeforeground': 
'SystemButtonText', 'anchor': 'center', 'background': 'SystemButtonFace', 
'bd': <pixel object: '2'>, 'bg': 'SystemButtonFace', 'bitmap': '', 
'borderwidth': <pixel object: '2'>, 'command': '100260920point', 'compound': 
'none', 'cursor': '', 'default': 'disabled', 'disabledforeground': 
'SystemDisabledText', 'fg': 'SystemButtonText', 'font': 'TkDefaultFont', 
'foreground': 'SystemButtonText', 'height': 0, 'highlightbackground': 
'SystemButtonFace', 'highlightcolor': 'SystemWindowFrame', 
'highlightthickness': <pixel object: '1'>, 'image': '', 'justify': 'center', 
'overrelief': '', 'padx': <pixel object: '1'>, 'pady': <pixel object: '1'>, 
'relief': 'raised', 'repeatdelay': 0, 'repeatinterval': 0, 'state': 
'normal', 'takefocus': '', 'text': 'Click me for 10 points!', 
'textvariable': '', 'underline': -1, 'width': 125, 'wraplength': <pixel 
object: '0'>}
#this will not work if you have closed the tkinter window

正如您所看到的,这是一个包含大量数值的字典,如果要更改任何按钮,只需执行以下操作:

Button_that_needs_to_be_changed["text"] = "new text here"

就是这样了!

它会自动更改按钮上的文本,即使您处于IDLE状态!


3

使用myButtonObject["text"] = "Hello World"

Python 3

from tkinter import *

btnMyButton = Button(text="Im Button", command=onClick)
btnMyButton["text"] = "Im not button"

python 2

import Tkinter as tk

btnMyButton = tk.Button(text="Im Button", command=onClick)
btnMyButton["text"] = "Im not button"

2
另一种方法是通过btn.configure(text="新文本"),就像这样:
import tkinter as tk
root = tk.Tk()

def update_btn_text():
    if(btn["text"]=="a"):
        btn.configure(text="b")
    else:
        btn.configure(text="a")


btn = tk.Button(root, text="a", command=update_btn_text)
btn.pack()

root.mainloop()

1
我认为这段代码对你会有用。
import tkinter 
from tkinter import *
#These Necessary Libraries

App = Tk()
App.geometry("256x192")

def Change():
    Btn1.configure(text=Text.get()) # Changes Text As Entry Message.
    Ent1.delete(first=0, last=999) # Not necessary. For clearing Entry.

Btn1 = Button(App, text="Change Text", width=16, command=Change)
Btn1.pack()

Text = tkinter.StringVar() # For Pickup Text

Ent1 = Entry(App, width=32, bd=3, textvariable=Text) #<-
Ent1.pack()

App.mainloop()

-1
from tkinter import *

BoardValue = ["-","-","-","-","-","-","-","-","-"]

window = Tk()
window.title("Noughts And Crosses")
window.geometry("10x200")

v = StringVar()
Label(window, textvariable=v,pady=10).pack()
v.set("Noughts And Crosses")

btn=[]

class BoardButton():
    def __init__(self,row_frame,b):
        global btn
        self.position= len(btn)
        btn.append(Button(row_frame, text=b, relief=GROOVE, width=2,command=lambda: self.callPlayMove()))
        btn[self.position].pack(side="left")

    def callPlayMove(self):
        PlayMove(self.position)

def DrawBoard():
    for i, b in enumerate(BoardValue):
        global btn
        if i%3 == 0:
            row_frame = Frame(window)
            row_frame.pack(side="top")
        BoardButton(row_frame,b)
        #btn.append(Button(row_frame, text=b, relief=GROOVE, width=2))
        #btn[i].pack(side="left")

def UpdateBoard():
    for i, b in enumerate(BoardValue):
        global btn
        btn[i].config(text=b)

def PlayMove(positionClicked):
    if BoardValue[positionClicked] == '-':
        BoardValue[positionClicked] = "X"
    else:
        BoardValue[positionClicked] = '-'
    UpdateBoard()

DrawBoard()
window.mainloop()

设置小部件的文本和获取其文本之间的不对称性令人沮丧。后者需要在引号中使用“text”,而前者则不需要。 - Jonathan Allin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接