python - 使图像充当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 文件,谢谢。
解决方案
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')
我在上面的类下创建了这个新类,它仍然不起作用,如果可能的话,你能写出代码以帮助我理解
推荐阅读
- excel - VBA 错误 438 对象在尝试从网站抓取网页时不支持此属性或方法
- angular - 无法在 peerjs 上关闭对等点之间的连接
- php - 在 laravel-8 中获取最后一个 id 表单数据库
- c# - 如何使用cefsharp在选项卡控件中打开链接标签?
- java - Treap Add 功能的实现
- c# - 我如何将直播流发送到抽搐
- spring - 如何在 elasticsearch 中创建文档以保存数据并进行搜索?
- flutter - _ceil() & _round() 与 Flutter 中的 lodash JavaScript 实用程序库相同
- javascript - 为什么我的 decipher.update 返回一个函数而不是解密的文本?节点JS
- r - R 中是否有一个不是二元运算的 Reduce 运算符?