在GUI中嵌入SAMP集线器#

概述#

如果希望在Python图形用户界面(GUI)工具中嵌入SAMP集线器,则需要使用以下命令以编程方式启动该集线器:

from astropy.samp import SAMPHubServer
hub = SAMPHubServer()
hub.start()

这将在线程中启动集线器,并且是非阻塞的。如果您对来自web SAMP客户端的连接不感兴趣,那么可以使用:

from astropy.samp import SAMPHubServer
hub = SAMPHubServer(web_profile=False)
hub.start()

这应该是你需要做的。但是,如果希望保持Web概要文件的活动状态,还有一个额外的考虑:当Web SAMP客户端连接时,您需要询问用户是否接受连接(出于安全原因)。默认情况下,确认消息是终端中基于文本的消息,但是如果您有GUI工具,您可能希望打开GUI对话框。

为此,需要定义一个处理对话框的类,然后传递 实例 全班同学 SAMPHubServer (不是类本身)。此类应继承自 astropy.samp.WebProfileDialog 并添加以下内容:

  1. 定期调用的GUI计时器回调 WebProfileDialog.handle_queue (可用作 self.handle_queue

  2. A show_dialog 方法显示同意对话框。它应该采用以下参数:

    • samp_name :发出请求的应用程序的名称。

    • details :有关发出请求的客户端的详细信息的字典。在这个字典中,SAMP标准要求的唯一键是 samp.name 提供发出请求的客户端的名称。

    • client :包含客户端地址的主机名、端口对。

    • origin :包含请求来源的字符串。

  3. 根据用户的响应 show_dialog 应该打电话 WebProfileDialog.consentWebProfileDialog.reject . 在某些情况下,GUI可能是回调的结果。

在Tk应用程序中嵌入SAMP集线器的示例#

以下代码是Tk应用程序的完整示例,它监视web SAMP连接并打开适当的对话框:

import tkinter as tk
import tkinter.messagebox as tkMessageBox

from astropy.samp import SAMPHubServer
from astropy.samp.hub import WebProfileDialog

MESSAGE = """
A Web application which declares to be

Name: {name}
Origin: {origin}

is requesting to be registered with the SAMP Hub.  Pay attention
that if you permit its registration, such application will acquire
all current user privileges, like file read/write.

Do you give your consent?
"""

class TkWebProfileDialog(WebProfileDialog):
    def __init__(self, root):
        self.root = root
        self.wait_for_dialog()

    def wait_for_dialog(self):
        self.handle_queue()
        self.root.after(100, self.wait_for_dialog)

    def show_dialog(self, samp_name, details, client, origin):
        text = MESSAGE.format(name=samp_name, origin=origin)

        response = tkMessageBox.askyesno(
            'SAMP Hub', text,
            default=tkMessageBox.NO)

        if response:
            self.consent()
        else:
            self.reject()

# Start up Tk application
root = tk.Tk()
tk.Label(root, text="Example SAMP Tk application",
         font=("Helvetica", 36), justify=tk.CENTER).pack(pady=200)
root.geometry("500x500")
root.update()

# Start up SAMP hub
h = SAMPHubServer(web_profile_dialog=TkWebProfileDialog(root))
h.start()

try:
    # Main GUI loop
    root.mainloop()
except KeyboardInterrupt:
    pass

h.stop()

如果您运行上述脚本,将打开一个窗口,显示“Example SAMP Tk application.”(示例SAMP Tk应用程序)。如果您随后转到以下页面,例如:

http://astrojs.github.io/sampjs/examples/pinger.html

然后单击Ping按钮,您将看到在Tk应用程序中打开的对话框。一旦你点击“确认”,以后的“Ping”呼叫将不再弹出对话框。