Python Gtk显示和隐藏imag

2024-04-19 11:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我是GTK的新手,我想知道当我点击窗口时如何在(x,y)处显示图像。 我放了一个图片.show()和图像.隐藏()但什么也没有出现。。。你知道吗

from gi.repository import Gtk
import time

def callback(window, event):
    print ('Clicked at x=', event.x, "and y=", event.y)
    image.show()
    time.sleep(0.2)
    image.hide() 

image = Gtk.Image()
image.set_from_file("C:\\Users\\alimacher\\FF0000.png")

window = Gtk.Window()

window.set_title('Dalle Test')

window.set_size_request(320, 240)

window.connect('button-press-event', callback)
window.connect('destroy', lambda w: Gtk.main_quit())
window.show_all()
Gtk.main()

谢谢你。你知道吗


Tags: from图像imageimporteventgtktimemain
2条回答

下面是我以为你要写的程序。它显示您单击的图像,然后使其在0.2秒后消失。如果再耽搁一段时间,会更有趣。你知道吗

EventBox是必需的,因为无论是窗口还是Fixed都不会发出button press事件,尽管它们是小部件。在后一个版本中,这可能比我的版本有所改变,所以可以省略它。但我的机器上没有它代码就不能工作。你知道吗

对EventBox和Fixed调用show是多余的,因为window.show_all()将显示它们,因为它们当时是树的一部分。但是,除非您使用的是GTK版本,其中的小部件默认显示而不是隐藏,否则图像上的show调用就不是。因为图像当时不存在。你知道吗

from gi.repository import Gtk, GLib

window = Gtk.Window()
window.set_title('Dalle Test')
window.set_size_request(320, 240)

eventbox = Gtk.EventBox()
window.add(eventbox)

fixed = Gtk.Fixed()

eventbox.add(fixed)

def callback(window, event, *data):
    print('Clicked at x=', event.x, "and y=", event.y)
    image = Gtk.Image()
    image.show()
    image.set_from_file("FF0000.png")
    image.set_size_request(64,64)
    fixed.put(image, int(event.x), int(event.y))

    def remove():
        fixed.remove(image)
    GLib.timeout_add(200, remove)

eventbox.connect('button-press-event', callback)

window.connect('destroy', lambda w: Gtk.main_quit())
window.show_all()
Gtk.main()

由于Gtk主循环,您不能使用时间。睡眠. 而是像这样使用超时:

from gi.repository import GLib
....
image.show()
GLib.timeout_add(200, image.hide)

除此之外,您没有使用window.add(image)将图像添加到窗口中

相关问题 更多 >