Python 3,Tkinter,如何更新button tex

2024-09-28 19:31:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使它,以便当用户点击一个按钮,它成为“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()

Tags: and用户defwindow按钮framesidepack
3条回答

总结这条线索。button.configbutton.configure都工作了!。

button.config(text="hello")
or
button.configure(text="hello")

与标签一样,Button小部件也有一个textvariable=选项。您可以使用StringVar.set()更新按钮。最小示例:

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

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"

真的是这样!

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

相关问题 更多 >