2017-03-08 63 views
0

我要回调,在下面的代码PyGTK如何将不同的回调绑定到标签上的每个可点击的文本?

import gi 
gi.require_version('Gtk', '3.0') 
from gi.repository import Gtk as gtk 
from gi.repository import Gdk as gdk 

def hello(*args): 
    print "hello, this is most used text editor for pyton" 

def wellcome(*args): 
    print "wellcome to the our program please update to premium version" 


w = gtk.Window(title = "example", type = gtk.WindowType.TOPLEVEL) 
w.resize(300, 200) 

mylabel = gtk.Label() 
mylabel.set_markup("""please read """ 
        """<span underline = "single" command = "hello">hello</span> or """ 
        """<span underline = "single" command = "wellcome">wellcome</span>""") 


w.add(mylabel) 
w.show_all() 
gtk.main() 

我知道,攀高跨度属性不包含的命令选项,好连接到标签

例如文本。有没有另一种方式来做到这一点?

+0

您需要使用两个'Gtk.Button's并连接到他们的'clicked'信号。 – elya5

+0

@ elya5,你能举个例子吗? –

回答

1

您可以通过将您的处理程序连接到activate-link信号来实现此目的。请注意,回调的签名与按钮点击不同,您应该返回True以停止进一步处理。

import gi 

gi.require_version('Gtk', '3.0') 
from gi.repository import Gtk 

class MyWindow(Gtk.Window): 

    def __init__(self): 
     Gtk.Window.__init__(self, title="Hello World") 

     label = Gtk.Label() 
     label.set_markup('<a href="mylink">Click Here</a> but not here.') 
     label.connect("activate-link", self.on_link_clicked) 
     self.add(label) 

    def on_link_clicked(self, label, uri): 
     print("%s clicked" % uri) 
     return True 

win = MyWindow() 
win.connect("delete-event", Gtk.main_quit) 
win.show_all() 
Gtk.main() 
+0

感谢您的回答,但这个答案并不能解决我的问题,即下划线(可点击)标签打开浏览器上的链接。我不希望它在浏览器中打开 –

+0

您是否在回调中返回True?请按照写入的内容准确运行我的代码,或发布您的代码。 – bohrax

+0

是的,它运作良好。但有一个小问题。我怎样才能绑定不同的回调每个可点击的文本? –

0
import gi 
gi.require_version('Gtk', '3.0') 
from gi.repository import Gtk 

class MyWindow(Gtk.Window): 

    def __init__(self): 
     Gtk.Window.__init__(self, title="Hello World") 

     label = Gtk.Label() 
     label.set_markup('please read <a href="hello">Hello</a> or <a href="wellcome">wellcome</a>') 
     label.connect("activate-link", self.on_link_clicked) 
     self.add(label) 

    def hello(self): 
     print "hello, this is most used text editor for pyton" 

    def wellcome(self): 
     print "wellcome to the our program please update to premium version" 

    def on_link_clicked(self, label, uri): 
     print("%s clicked" % uri) 

     if uri == "hello": 
      self.hello() 
     elif uri == "wellcome": 
      self.wellcome() 

     return True 

win = MyWindow() 
win.connect("delete-event", Gtk.main_quit) 
win.show_all() 
Gtk.main() 
相关问题