【问题标题】:Changing a canvas object's color using a button tkinter使用按钮 tkinter 更改画布对象的颜色
【发布时间】:2019-02-23 12:36:48
【问题描述】:

我无法让按钮在 python 3 中按预期工作。也就是说,当按下它时,它会将圆圈的颜色从一种颜色更改为另一种颜色,从红色开始。然而,当我运行这个程序时,它只是以白色而不是红色开始,按下按钮也不会改变圆圈的颜色,我很困惑为什么。

from tkinter import *

def changeColor():
    test.itemconfig(circle, fill = "blue")

def changeColor2():
    test.itemconfig(circle, fill = "white")

root = Tk()
test = Canvas(root, width = 50, height = 50)
test.pack()
circle = test.create_oval(0, 0, 25, 25,fill="red")



button = Button(root,text="",command=changeColor(),bg= "blue")
button2= Button(root,text="",command=changeColor2(),bg= "white")
button.pack()
button2.pack()

root.mainloop()

【问题讨论】:

    标签: python tkinter tkinter-canvas


    【解决方案1】:

    From Wikibooks on Python

    在 Python 中可以使用闭包,因为函数是一等对象。函数只是函数类型的对象。作为对象意味着可以将函数对象(未调用的函数)作为参数或返回值传递,或者为函数对象分配另一个名称。使闭包有用的一个独特功能是封闭函数可以使用在父函数作用域中定义的名称。

    传递函数的语法是不带括号的函数名: 命令=改变颜色

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-22
      • 2016-11-07
      • 2016-05-26
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多