sonist-gtk/ui/image_button.py

56 lines
1.4 KiB
Python
Raw Normal View History

2023-08-17 20:51:59 +08:00
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
2023-08-18 00:09:43 +08:00
from gi.repository import Gtk, Gdk
2023-08-17 20:51:59 +08:00
from .image import ScaleImage
class ImageButton(Gtk.Button):
def __init__(self, filepath, width = 26, height = 26):
Gtk.Button.__init__(self)
2023-08-18 19:04:51 +08:00
self.width = width
self.height = height
self._image_path = None
2023-08-17 20:51:59 +08:00
self.set_name('ImageButton')
self.set_size_request(width, height)
2023-08-18 19:04:51 +08:00
self.set_valign(Gtk.Align.CENTER)
2023-08-17 20:51:59 +08:00
2023-08-18 00:09:43 +08:00
# 针对macos的设置, 但只解决了普通状态下的边框问题, 鼠标经过的样式还在
self.set_relief(Gtk.ReliefStyle.NONE)
2023-08-18 19:04:51 +08:00
self.set_image(filepath)
2023-08-17 20:51:59 +08:00
css_provider = Gtk.CssProvider()
style = f"""
2023-08-18 19:04:51 +08:00
#ImageButton {{
2023-08-17 20:51:59 +08:00
border: 0;
2023-08-18 19:04:51 +08:00
border-radius: 50%;
2023-08-17 20:51:59 +08:00
background-color: transparent;
2023-08-18 00:09:43 +08:00
border-color:transparent;
outline: transparent;
2023-08-17 20:51:59 +08:00
}}
2023-08-18 19:04:51 +08:00
#ImageButton:hover {{
background-color: rgba(255,255,255,.1);
2023-08-22 20:43:40 +08:00
outline: transparent;
box-shadow:none;
2023-08-18 19:04:51 +08:00
}}
2023-08-17 20:51:59 +08:00
"""
css_provider.load_from_data(style.encode('UTF-8'))
context = self.get_style_context()
context.add_provider(css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)
2023-08-18 19:04:51 +08:00
2023-08-21 19:06:22 +08:00
2023-08-18 19:04:51 +08:00
def set_image(self, filepath):
if self._image_path == filepath:
return
self._image_path = filepath
image = ScaleImage(filepath)
image.resize(self.width, self.height)
Gtk.Button.set_image(self, image)
return self