Kivy在屏幕尺寸变化时更新图像

2 投票
1 回答
2697 浏览
提问于 2025-04-18 13:11

我的问题是这样的。我有一张背景图片,效果很好,当我调整窗口大小时,图片也会按照设计的方式移动。但是在我的登录类中,'check-icon.png'根本不显示。日志上说它已经加载了,但在窗口的任何地方都看不到它。而且,当我把登录类的代码改成:

with self.canvas.before:
    self.image = Image(stuff)

而不是

with root.canvas.before:
    self.image = Image(stuff)

(这里把root改成self),我可以让check-icon.png显示出来,但它在窗口大小变化时并没有像背景图片那样重新对齐。

import kivy
kivy.require('1.8.0') # current kivy version
import ConfigParser
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.image import Image
from kivy.graphics import Rectangle


class login(Widget):
    #checking to see if the user logging in has privilage to access program
    def validate(self, *args):

        username = self.ids['user']
        user = username.text
        config = ConfigParser.ConfigParser()
        config.read('Privilage.cfg')

        if not config.has_section('users'):
            print 'the Privilage.cfg file has been tampered with'

        if not config.has_option('users',user):
            print 'user is not listed'
        else:
            userPriv = config.get('users',user)
            print 'user',user,'has privilage',userPriv
            valid = '/Users/Kevin/Desktop/Python-extras/SSS Assistant/Manager_images/check-icon.png'

        #Put a check or x next to username based on if its in the system
        self.root = root = login()
        root.bind(size=self._update_image,pos=self._update_image)
        with root.canvas.before:
            self.image = Image(source=valid, pos=((self.width / 2)+130,(self.top / 2)), size=(25,25))


    def _update_image(self,instance,value):
        self.image.pos = instance.pos
        self.image.size = instance.size

class DataApp(App):
    def build(self):
        #login is the root Widget here
        self.root = root = login()
        root.bind(size=self._update_rect,pos=self._update_rect)
        with root.canvas.before:
            self.rect = Rectangle(source="/Users/Kevin/Desktop/Python-extras/SSS Assistant/Manager_images/background.jpg",size=root.size,pos=root.pos)
        return root

    def _update_rect(self,instance,value):
        self.rect.pos = instance.pos
        self.rect.size = instance.size



if __name__ == '__main__':
    DataApp().run()

另外,抱歉我发了这么长的内容。我知道我应该只发相关的代码,但因为我还是新手,所以想确保错误不是出现在代码的其他地方。

新的代码是:

    self.bind(size=self._update_image,pos=self._update_image)
    #Put a check or x next to username based on if its in the system
    self.image = self.add_widget(Image(source=valid, pos=((self.width / 2)+115,(self.top / 2)+50), size=(20,20)))



def _update_image(self,instance,value):
    self.image.pos = instance.pos
    self.image.size = instance.size

1 个回答

2

你把更新大小的函数绑定到了自定义的根节点上,但这个根节点是一个login的实例,它从来没有被添加到界面树中,也没有做任何事情——特别是,它的大小从来没有改变,所以更新也就不会发生。

你应该直接绑定到self,也就是self.bind(pos=...)

另外,你的控件名称应该以大写字母开头,这不仅是一个好的Python习惯,而且在kv语言中也依赖这个来区分控件和属性……而且你可能会希望尽可能多地使用kv语言!

撰写回答