Python 3,Tkinter,如何更新按钮文本 [英] Python 3, Tkinter, How to update button text

查看:80
本文介绍了Python 3,Tkinter,如何更新按钮文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让它在用户点击按钮时变成X"或0"(取决于他们的团队).我怎样才能使按钮上的文本更新?到目前为止,我最好的想法是删除按钮然后再次打印它们,但这只会删除一个按钮.这是我到目前为止所拥有的:

Im trying to make it so that when the user clicks a button, it becomes "X" or "0" (Depending on their team). How can I make it so that the text on the button is updated? My best idea so far has been to delete the buttons then print them again, but that only deletes one button. Here's what I have so far:

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

推荐答案

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

The Button widget, just like your Label, also has a textvariable= option. You can use StringVar.set() to update the Button. Minimal example:

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

这篇关于Python 3,Tkinter,如何更新按钮文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆