【问题标题】:Tkinter Canvas will not update color change via itemconfigTkinter Canvas 不会通过 itemconfig 更新颜色变化
【发布时间】:2016-06-06 14:40:56
【问题描述】:

我正在做一个项目,该项目处理一种地图,其中有一些线作为路径。这些路径可以有两种状态,活动和非活动,颜色不同。有一种方法可以改变填充颜色。 我不知道为什么我的画布线不会更新。这是我的简化代码:

import Tkinter

inactive = "#385c61"
active = "#7dd5cd"

map = Tkinter.Canvas()

class GuiPart(object):

    def __init__(self, master):
        #some code

    def initGui(self, master):
        map = Tkinter.Canvas(left, width=660, height=600, bg="#35424b", bd="0", highlightthickness="0")
        map.pack()
        global inactive, active
        pathA = map.create_line(135, c, 135, e, fill=inactive, width=w)

    def setActivePath(self):
        global active, inactive
        map.itemconfig(pathA, fill=active)
        map.update_idletasks()
        map.update()

root = Tkinter.Tk()
gui = GuiPart(root)
gui.initGui(root)

gui.setActivePath()

root.mainloop()

如果我在initGui 中使用itemconfig 更改颜色,它应该可以正常工作,但后来我必须从另一个类调用setActivePath,所以它必须是一个自己的方法。 (我知道我给map = Tkinter.Canvas(...) 打了两次电话,否则我得到一个错误,也必须修复它)

有什么想法吗?

【问题讨论】:

  • 嗯,现在我在 R. Murray 的帮助下更改了代码后,如果我删除画布的第一个调用,我不会收到错误消息。但主要问题,即颜色没有改变仍然存在......
  • @forever_engineer 我正在处理它。
  • 尝试清除 class typenamespace 方法。您想访问 loop 内部元素(可以在内部调用(鼠标事件、按钮等))!

标签: python canvas tkinter


【解决方案1】:

您需要为该类设置mappathA 属性,以便setActivePath 可以引用它。这就是为什么您在必须创建两个画布时遇到错误的原因。

import Tkinter

inactive = "#385c61"
active = "#7dd5cd"

class GuiPart(object):

    def __init__(self, master):       
        #some code

    def initGui(self, master):                     
        self.map = Tkinter.Canvas(left, width=660, height=600, bg="#35424b", bd="0", highlightthickness="0")
        self.map.pack()    
        global inactive, active
        self.pathA = map.create_line(135, c, 135, e, fill=inactive, width=w)

    def setActivePath(self):
        global active, inactive
        self.map.itemconfig(self.pathA, fill=active)
        self.map.update_idletasks()
        self.map.update()

root = Tkinter.Tk()
gui = GuiPart(root)            
gui.initGui(root)

gui.setActivePath()

root.mainloop()

在我看来,其他一切都很好,尽管您说这并没有解决您的问题。据我所知,self.map.itemconfig(self.pathA, fill=active) 是正确使用此方法(请参阅herehere),因此您的问题可能不在您发布的代码范围内。我无法正确测试代码,因为您没有将代码包含在 __init__ 方法中,并且因为在我使用六年级的计算机上只安装了 Python 3.4.1。请编辑您的问题以将代码包含在 __init__ 方法中。

【讨论】:

  • 您好,感谢您的快速回复!但这似乎不起作用......线条的颜色没有更新。
  • @forever_engineer 请阅读编辑后的答案并按要求编辑您的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-08
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-01
  • 2022-12-17
相关资源
最近更新 更多