在 PyGTK 中按下按钮后如何更新菜单?

发布于 2024-10-06 16:36:17 字数 3651 浏览 3 评论 0原文

我对 PyGTK 不太熟悉。请看下面的代码。是否可以让它执行以下操作?

  1. 有两个按钮,我们称之为“生成”和“查看”。
  2. “生成”按钮将为变量 A 和 B 生成随机值。
  3. “查看”按钮将弹出一个显示 A 和 B 的菜单。

以下代码的问题是“查看”菜单显示 A 和 B,但当用户按下“生成”按钮时,菜单不会更新。

我使用 Python 2.6.6 运行代码。

还请建议我改进代码的任何方法(格式、样式、PyGTK 约定,...)。先感谢您。

   """Generate values for two variables A and B."""
# ------------------------------------------------------------------------------
# Winston C. Yang
# Created 2010-12-04
# ------------------------------------------------------------------------------
# Python modules. Be alphabetical.
import random
# ------------------------------------------------------------------------------
# Other Python modules. Be alphabetical.
import gtk
import pygtk
pygtk.require("2.0")
# ------------------------------------------------------------------------------
class Generator:

    """Generate values for two variables A and B."""

    def __init__(self):

        # Create a dictionary in which a key is a variable name and a
        # (dictionary) value is the variable value.
        self.d_variable_value = {}
        # ----------------------------------------------------------------------
        window = gtk.Window()
        window.set_title("Generate")
        window.connect("destroy", self.quit_event)
        # ----------------------------------------------------------------------
        # Create a vertical box with two buttons.
        vbox = gtk.VBox()

        # Create a button to generate values for A and B.
        b = gtk.Button("Generate A and B")
        vbox.pack_start(b)
        b.connect("clicked", self.generate_variable_values)

        # Create a button to view A and B.
        b = gtk.Button("View A and B")
        vbox.pack_start(b)
        b.connect_object("event", self.button_press, self.create_menu())
        # ----------------------------------------------------------------------
        window.add(vbox)
        window.show_all()
    # --------------------------------------------------------------------------
    def quit_event(self, widget=None, event=None):
        """Quit."""
        gtk.main_quit()
    # --------------------------------------------------------------------------
    def generate_variable_values(self, widget=None):
        """Generate values for A and B."""
        self.d_variable_value = {
            "A" : random.randint(0, 10),
            "B" : random.randint(0, 10),
            }

        print "I generated " + str(self.d_variable_value)
    # --------------------------------------------------------------------------
    def button_press(self, widget, event):
        """button_press method."""
        if event.type == gtk.gdk.BUTTON_PRESS:
            widget.popup(None, None, None, event.button, event.time)
            return True

        return False
    # --------------------------------------------------------------------------
    def create_menu(self):
        """Create a menu showing A and B."""
        # How can I update the menu after the user presses the
        # "generate" button?

        # If there are no values for A and B, generate them.
        if not self.d_variable_value:
            self.generate_variable_values()

        # Show A and B in a menu.
        menu = gtk.Menu()

        for key, value in sorted(self.d_variable_value.items()):

            text = key + " " + str(value)
            item = gtk.MenuItem(text)
            item.show()
            menu.append(item)

        return menu
# ------------------------------------------------------------------------------
if __name__ == "__main__":
    Generator()
    gtk.main()

I am not that familiar with PyGTK. Please see the following code. Is it possible to make it do the following?

  1. There are two buttons, which we refer to as "generate" and "view".
  2. The "generate" button will generate random values for variables A and B.
  3. The "view" button will pop up a menu showing A and B.

The problem with the following code is that the "view" menu shows A and B, but the menu does not update as the user presses the "generate" button.

I ran the code with Python 2.6.6.

Please also suggest any ways that I can improve the code (formatting, style, PyGTK conventions, ...). Thank you in advance.

   """Generate values for two variables A and B."""
# ------------------------------------------------------------------------------
# Winston C. Yang
# Created 2010-12-04
# ------------------------------------------------------------------------------
# Python modules. Be alphabetical.
import random
# ------------------------------------------------------------------------------
# Other Python modules. Be alphabetical.
import gtk
import pygtk
pygtk.require("2.0")
# ------------------------------------------------------------------------------
class Generator:

    """Generate values for two variables A and B."""

    def __init__(self):

        # Create a dictionary in which a key is a variable name and a
        # (dictionary) value is the variable value.
        self.d_variable_value = {}
        # ----------------------------------------------------------------------
        window = gtk.Window()
        window.set_title("Generate")
        window.connect("destroy", self.quit_event)
        # ----------------------------------------------------------------------
        # Create a vertical box with two buttons.
        vbox = gtk.VBox()

        # Create a button to generate values for A and B.
        b = gtk.Button("Generate A and B")
        vbox.pack_start(b)
        b.connect("clicked", self.generate_variable_values)

        # Create a button to view A and B.
        b = gtk.Button("View A and B")
        vbox.pack_start(b)
        b.connect_object("event", self.button_press, self.create_menu())
        # ----------------------------------------------------------------------
        window.add(vbox)
        window.show_all()
    # --------------------------------------------------------------------------
    def quit_event(self, widget=None, event=None):
        """Quit."""
        gtk.main_quit()
    # --------------------------------------------------------------------------
    def generate_variable_values(self, widget=None):
        """Generate values for A and B."""
        self.d_variable_value = {
            "A" : random.randint(0, 10),
            "B" : random.randint(0, 10),
            }

        print "I generated " + str(self.d_variable_value)
    # --------------------------------------------------------------------------
    def button_press(self, widget, event):
        """button_press method."""
        if event.type == gtk.gdk.BUTTON_PRESS:
            widget.popup(None, None, None, event.button, event.time)
            return True

        return False
    # --------------------------------------------------------------------------
    def create_menu(self):
        """Create a menu showing A and B."""
        # How can I update the menu after the user presses the
        # "generate" button?

        # If there are no values for A and B, generate them.
        if not self.d_variable_value:
            self.generate_variable_values()

        # Show A and B in a menu.
        menu = gtk.Menu()

        for key, value in sorted(self.d_variable_value.items()):

            text = key + " " + str(value)
            item = gtk.MenuItem(text)
            item.show()
            menu.append(item)

        return menu
# ------------------------------------------------------------------------------
if __name__ == "__main__":
    Generator()
    gtk.main()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

江南烟雨〆相思醉 2024-10-13 16:36:17

此行 b.connect_object("event", self.button_press, self.create_menu())self.button_press 连接到 event 信号在由 self.create_menu() 创建的 gtk.Menu 上。该行永远不会再次执行,因此菜单始终相同。

我所做的是将 View A 和 B 按钮的 event 信号连接到 self.button_press 处理程序,并且该处理程序创建一个更新的菜单每次运行时。

# ------------------------------------------------------------------------------
# Python modules. Be alphabetical.
import random
# ------------------------------------------------------------------------------
# Other Python modules. Be alphabetical.
import gtk
import pygtk
pygtk.require("2.0")
# ------------------------------------------------------------------------------
class Generator:

    """Generate values for two variables A and B."""

    def __init__(self):

        # Create a dictionary in which a key is a variable name and a
        # (dictionary) value is the variable value.
        self.d_variable_value = {}
        # ----------------------------------------------------------------------
        window = gtk.Window()
        window.set_title("Generate")
        window.connect("destroy", self.quit_event)
        # ----------------------------------------------------------------------
        # Create a vertical box with two buttons.
        vbox = gtk.VBox()

        # Create a button to generate values for A and B.
        b = gtk.Button("Generate A and B")
        vbox.pack_start(b)
        b.connect("clicked", self.generate_variable_values)

        # Create a button to view A and B.
        b = gtk.Button("View A and B")
        vbox.pack_start(b)
        b.connect("event", self.button_press)
        # ----------------------------------------------------------------------
        window.add(vbox)
        window.show_all()
    # --------------------------------------------------------------------------
    def quit_event(self, widget=None, event=None):
        """Quit."""
        gtk.main_quit()
    # --------------------------------------------------------------------------
    def generate_variable_values(self, widget=None):
        """Generate values for A and B."""
        self.d_variable_value = {
            "A" : random.randint(0, 10),
            "B" : random.randint(0, 10),
            }

        print "I generated " + str(self.d_variable_value)
    # --------------------------------------------------------------------------
    def button_press(self, button, event):
        """button_press method."""
        if event.type == gtk.gdk.BUTTON_PRESS:
            menu = self.create_menu()
            menu.popup(None, None, None, event.button, event.time)
            return True

        return False
    # --------------------------------------------------------------------------
    def create_menu(self):
        """Create a menu showing A and B."""
        # How can I update the menu after the user presses the
        # "generate" button?

        # If there are no values for A and B, generate them.
        if not self.d_variable_value:
            self.generate_variable_values()

        # Show A and B in a menu.
        menu = gtk.Menu()

        print self.d_variable_value
        for key, value in sorted(self.d_variable_value.items()):

            text = key + " " + str(value)
            item = gtk.MenuItem(text)
            item.show()
            menu.append(item)

        return menu
# ------------------------------------------------------------------------------
if __name__ == "__main__":
    Generator()
    gtk.main()

This line b.connect_object("event", self.button_press, self.create_menu()) is connecting self.button_press to the event signal on a gtk.Menu created by self.create_menu(). This line is never executed again, so the menu is always the same.

What I did was connect the event signal for the View A and B button to the self.button_press handler, and that handler creates an updated menu every time it's run.

# ------------------------------------------------------------------------------
# Python modules. Be alphabetical.
import random
# ------------------------------------------------------------------------------
# Other Python modules. Be alphabetical.
import gtk
import pygtk
pygtk.require("2.0")
# ------------------------------------------------------------------------------
class Generator:

    """Generate values for two variables A and B."""

    def __init__(self):

        # Create a dictionary in which a key is a variable name and a
        # (dictionary) value is the variable value.
        self.d_variable_value = {}
        # ----------------------------------------------------------------------
        window = gtk.Window()
        window.set_title("Generate")
        window.connect("destroy", self.quit_event)
        # ----------------------------------------------------------------------
        # Create a vertical box with two buttons.
        vbox = gtk.VBox()

        # Create a button to generate values for A and B.
        b = gtk.Button("Generate A and B")
        vbox.pack_start(b)
        b.connect("clicked", self.generate_variable_values)

        # Create a button to view A and B.
        b = gtk.Button("View A and B")
        vbox.pack_start(b)
        b.connect("event", self.button_press)
        # ----------------------------------------------------------------------
        window.add(vbox)
        window.show_all()
    # --------------------------------------------------------------------------
    def quit_event(self, widget=None, event=None):
        """Quit."""
        gtk.main_quit()
    # --------------------------------------------------------------------------
    def generate_variable_values(self, widget=None):
        """Generate values for A and B."""
        self.d_variable_value = {
            "A" : random.randint(0, 10),
            "B" : random.randint(0, 10),
            }

        print "I generated " + str(self.d_variable_value)
    # --------------------------------------------------------------------------
    def button_press(self, button, event):
        """button_press method."""
        if event.type == gtk.gdk.BUTTON_PRESS:
            menu = self.create_menu()
            menu.popup(None, None, None, event.button, event.time)
            return True

        return False
    # --------------------------------------------------------------------------
    def create_menu(self):
        """Create a menu showing A and B."""
        # How can I update the menu after the user presses the
        # "generate" button?

        # If there are no values for A and B, generate them.
        if not self.d_variable_value:
            self.generate_variable_values()

        # Show A and B in a menu.
        menu = gtk.Menu()

        print self.d_variable_value
        for key, value in sorted(self.d_variable_value.items()):

            text = key + " " + str(value)
            item = gtk.MenuItem(text)
            item.show()
            menu.append(item)

        return menu
# ------------------------------------------------------------------------------
if __name__ == "__main__":
    Generator()
    gtk.main()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文