首页 > 解决方案 > 使图像充当kivy中的按钮

问题描述

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput 
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image


 class FirstPage(GridLayout, ButtonBehavior, Image):
        def __init__(self, **kwargs): 
            super(FirstPage, self).__init__(**kwargs)
            
            self.cols =2
            self.row_force_default = True
            self.row_default_height = 100
            
            self.add_widget(Label(text='Enter Name: '))
            self.name = TextInput(multiline=False) 
            self.add_widget(self.name)
            
            self.submit_name = Button(text = 'Submit name', font_size = 30)
            self.submit_name.bind(on_press = self.sub_name)
            self.add_widget(Label())
            self.add_widget(self.submit_name) 
        
        def sub_name(self, instance):
            if self.name.text == '':
                name_error = Label(text= 'Please put your name')
                self.add_widget(Label())
                self.add_widget(name_error)
            else:
    
                name = Label(text = 'Hello' + ' ' + self.name.text)
                self.add_widget(Label())
                self.add_widget(name)
            
            
            self.inside = FloatLayout()
            
            self.inside.cols = 1
            self.add_widget(self.inside)
            
            self.title = Label(text ='[b]Please choose your country[/b] '  + f'[b]{self.name.text} 
            [/b]',pos=(200,200), markup=True )
            self.inside.add_widget(self.title)
            self.pic = Image(source='unitedkingdom.png', on_press=self.ha)
            self.inside.add_widget(self.pic)
            
        def ha(self, instance):
            print('ha')
    
            
            
            
    class WeatherApp(App):
        def build(self):
            return FirstPage()
        
        
        
        
    if __name__ == '__main__':
         WeatherApp().run()
            

我想让图像充当按钮,但是当我运行应用程序时,我得到一个随机的白框,并且我的图片没有作为按钮。这是否与我添加按钮行为的方式有关,任何建议都值得赞赏。此外,答案是否可以在 python 代码中,因为我的计算机有一些问题,不允许我使用 kv 文件,谢谢。

标签: pythonandroidbuttonkivyguid

解决方案


class united_k(ButtonBehavior, Image):
    def __init__(self, **kwargs): 
        super(united_k, self).__init__(**kwargs)
        
        
        self.pic = Image(source='unitedkingdom.png', on_press=self.ha)
        self.inside.add_widget(self.pic)
        
    def ha(self, instance):
        print('ha')

我在上面的类下创建了这个新类,它仍然不起作用,如果可能的话,你能写出代码以帮助我理解


推荐阅读