为了账号安全,请及时绑定邮箱和手机立即绑定

stringvar 如何与 textvariable 一起工作?

stringvar 如何与 textvariable 一起工作?

MM们 2022-06-02 14:41:08
我正在编写一个国际象棋程序,但我无法输出棋子,因为我将文本从使用文本定义为文本变量,现在我无法让字符串工作以输出棋子。我在 for 循环中定义按钮,它在正方形中不输出任何内容。代码是def drawboard(self):        x=0        y=0        for column in range(self.n):            self.changecolours()            x=x+1            y=0            for row in range(self.n):                y=y+1                colour = self.colours[self.colourindex]                pos=(x,9-y)                buttons=(tk.Button(self.boardframe, padx=10,  textvariable=lambda position=pos: self.placepieces(position), borderwidth=0, bg=colour,  relief="solid", font=self.piecefont, command=lambda position=pos: self.movepiece(position)  ))                buttons.grid(column=(x-1), row=(y-1), sticky="W"+"E"+"N"+"S" )                self.changecolours()    @classmethod    def placepieces(cls, position):        black=Black()        white=White()        squareposition=position        icon=tk.Stringvar("")        if squareposition in white.position.values():            for key in white.position:                value=white.position.get(key)                if value==squareposition:                    if key.endswith("pawn"):                        icon.set(white.pawntype[key])                    elif key=="king":                        icon.set(white.PIECES.get("KING"))                    elif key=="queen":                        icon.set(white.PIECES.get("QUEEN"))                    elif key.endswith("bishop"):                        icon.set(white.PIECES.get("BISHOP"))                    elif key.endswith("knight"):                        icon.set(white.PIECES.get("KNIGHT"))                    else:                        icon.set(white.PIECES.get("ROOK"))
查看完整描述

1 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

stringvar 如何与 textvariable 一起工作?

对于 Button,您可以将文本配置为以两种方式之一显示:使用硬编码字符串(例如:)text='click me'或使用textvariable属性。

textvariable属性必须设置为特殊 tkinter 变量对象之一的实例,StringVar或(例如:) 。当配置了这些变量之一的实例时,按钮上的文本将显示变量的值。IntVarDoubleVarBooleanVarvar=tk.StringVar(); Button(..., textvariable=var)

在内部,当您指定 a 时textvariable,tkinter 将采用该对象的字符串表示并在嵌入式解释器中创建一个 tcl 变量。因此,虽然它可能会接受标准变量、命令甚至 lambda,但最终会创建一个具有该名称的内部 tcl 变量,并将该内部变量与底层 tcl 小部件相关联。如果您不使用其中一个特殊变量,您将很难获取或设置该变量的值。

例如,考虑这组命令:

var = tk.StringVar(value="hello")
tk.Button(root, textvariable=var)

运行该代码时,按钮上显示的文本将为hello. 如果您随时更改变量(例如:var.set("goodbye")),按钮将自动更改为显示新值。


查看完整回答
反对 回复 2022-06-02
  • 1 回答
  • 0 关注
  • 185 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号