python - Python GTK resizing large image to fit inside a window
问题描述
Important note: I'm using PyGObject
to get access to the GTK widgets, not PyGTK
. That's what makes this question different from similar ones:
I want to make a very simple app that displays a label, an image and a button, all stacked on top of each other. The app should be running in fullscreen mode.
When I attempted it, I've run into a problem. My image is of very high resolution, so when I simply create it from file and add it, I can barely see 20% of it.
What I want is for this image to be scaled by width according to the size of the window (which is equal to the screen size as the app runs in fullscreen).
I've tried using Pixbufs, but calling scale_simple
on them didn't seem to change much.
Here's my current code:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GdkPixbuf
class Window(Gtk.Window):
def __init__(self):
super().__init__(title='My app')
layout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
dimensions = layout.get_allocation()
pixbuf = GdkPixbuf.Pixbuf.new_from_file('path/to/image')
pixbuf.scale_simple(dimensions.width, dimensions.height, GdkPixbuf.InterpType.BILINEAR)
image = Gtk.Image.new_from_pixbuf(pixbuf)
dismiss_btn = Gtk.Button(label='Button')
dismiss_btn.connect('clicked', Gtk.main_quit)
layout.add(image)
layout.add(dismiss_btn)
self.add(layout)
win = Window()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
解决方案
The problem is that scale_simple
actually returns a new Pixbuf, as per GTK+ docs.
Getting screen dimensions can be done by calling .get_screen()
on the window and then calling .width()
or .height()
on the screen object.
The whole code put together looks something like this:
screen = self.get_screen()
pixbuf = GdkPixbuf.Pixbuf.new_from_file('/path/to/image')
pixbuf = pixbuf.scale_simple(screen.width(), screen.height() * 0.9, GdkPixbuf.InterpType.BILINEAR)
image = Gtk.Image.new_from_pixbuf(pixbuf)
推荐阅读
- android - Android,如何打开相机,中间有一个计时器,从 10 到 0 计数,并且可以与之交互,从相机框架开始
- python - 如何创建一个函数来更改变量并使用更新的变量刷新 Kivy 应用程序
- python-3.x - 如何正确设置打印机的painter?
- excel - Excel - 根据列中的文本计数创建图表
- javascript - 如何在 Tensorflow.js 中删除模型?
- ruby-on-rails - HTTP Origin 标头 (http://app.example.local:8080) 与 request.base_url (http://app.example.local) 不匹配
- azure - 某些存储库的 Azure Devops 权限
- android - 共享(Activity/NavGraph-scoped)ViewModel 和 Fragment ViewModel 之间的通信
- node.js - 在 Node.js 应用程序中使用 GraphQL 从 Microsoft SQL Server 查询数据
- excel - 如何使用 VBA 从 powerpoint 中删除一个形状