python - Kivy 矩形源没有更新?
问题描述
(我已经阅读了很多关于此的其他帖子,但它们似乎对我没有帮助(或者我根本不理解它们))
我有一个函数 Add(),其中调用了另一个函数 Grid(),它创建了一个 Grid.png 文件并将其保存到我的桌面。这个 Add() 函数被多次调用(通过一个按钮),其中还有 Grid() 函数。这是一个小代码片段:
Width = 700
Height = 700
def __init__(self,**kwargs):
super(Drw, self).__init__(**kwargs)
self.CellCount = 1
time.sleep(0.5)
self.cellAdd= int(input("\nCells to add: "))
self.bg = ""
with self.canvas:
self.add = Button(text = "add", font_size =40, pos = (700,300))
self.sub = Button(text="sub", font_size=40, pos=(700, 400))
self.add.bind(on_press = self.Add)
self.sub.bind(on_press= self.Sub)
self.add_widget(self.sub)
self.add_widget(self.add)
def Add(self, instance):
self.CellCount += self.cellAdd
Grid(self.CellCount, self.Width, self.Height)
with self.canvas:
self.bg = Rectangle(source= r"C:\Users\Max\Desktop\Grid.png", pos=(0,0), size= (self.Width, self.Height))
self.L = Label(text=str(self.CellCount)+" columns", pos=(500, 300))
发生的情况是,当我第一次按下“添加”按钮时,它会执行应有的操作,因此会调用 Add(),然后调用 Grid() 并在我的桌面上创建一个新图像。然后创建“bg”(背景)并正确显示图像。然而,这只适用于 1 次。之后,当我继续按“添加”时,即使每次按“添加”时桌面上的 Grid.png 都发生了变化,也没有任何反应。图像只是没有以某种方式更新。路径始终保持不变,所以我不明白为什么它不会将图像更改为新图像?
我已经尝试使用手动更新源
self.bg.source = r"C:\Users\Max\Desktop\Grid.png"
但这无济于事。我对 Kivy 很陌生,所以如果有人问这个问题我很抱歉。
感谢您的阅读!
编辑 我用这个修复它:
def Add(self, instance):
self.CellCount += self.cellAdd
Grid(self.CellCount, self.Width, self.Height)
with self.canvas:
self.canvas.clear()
self.bg =Image(source= r"C:\Users\Max\Desktop\Grid.png", pos=(0,0), size= (self.Width, self.Height))
self.bg.reload()
self.L = Label(text=str(self.CellCount)+" columns", pos=(500, 300))
我仍然不知道为什么 Cache.remove() 不起作用,因为这对我来说似乎是合乎逻辑的,但至少 .reload() 工作得足够好。谢谢您的回答!
解决方案
可能图像源正在被 Kivy 的图像加载器缓存,因此您需要通知它更新。尝试from kivy.cache import Cache
和Cache.remove("kv.texture", your_filename)
(或省略your_filename
参数以清除整个纹理缓存)。
推荐阅读
- spring - 保存 null 时的 inputMask 设置为零
- ocaml - 使用不同类型的元组进行模式匹配
- javascript - 懒惰安装依赖是什么意思
- qt - QGraphicsItem 未呈现为 HiDPI
- ruby-on-rails - 如何在 Ruby on Rails 应用程序中实现 r 脚本
- javascript - 是否可以使用 Firebase Cloud Messaging API 列出所有推送通知?
- r - 取百分比向量并乘以列
- vba - 如何根据变量列在excel中通过VBA计算总和?
- java - 使用 Wildfly 在 Spring Boot 中配置 LDAP
- c++ - lambda函数中的参数列表类型错误