Mrc*_*och 0 python tkinter python-3.x
我试图使其成为当用户点击按钮时,它变为"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()
Run Code Online (Sandbox Code Playgroud)
Button小部件,就像您的Label一样,也有一个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()
Run Code Online (Sandbox Code Playgroud)
总结一下这个线程。button.config
并且button.configure
都工作!
button.config(text="hello")
or
button.configure(text="hello")
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它是一个很大的值字典,因此如果您想更改任何按钮,只需执行以下操作:
Button_that_needs_to_be_changed["text"] = "new text here"
Run Code Online (Sandbox Code Playgroud)
确实是这样!
即使您处于空闲状态,它也会自动更改按钮上的文本!