love萌萌loli 2020-02-17 11:25 采纳率: 0%
浏览 171

pygtk的button在click以后会调用回调函数,然后打开一个文件,那么怎么把这个文件的文件名字传递出来呢?

button1 = Gtk.Button("Choose File")

button1.connect("clicked", self.on_file_clicked)

box.add(button1)

self.on_file_clicked是一个可以打开文件的回调函数,但是现在我选择文件以后需要对文件显示出来,请问怎么做呢?

  • 写回答

2条回答 默认 最新

  • 码农阿豪@新空间 新星创作者: 前端开发技术领域 2024-07-25 20:54
    关注
    让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
    你可以通过使用Gtk.FileChooserDialog来打开文件,并在回调函数内读取文件内容并显示出来。 下面是一个示例代码:
    import gi
    gi.require_version('Gtk', '3.0')
    from gi.repository import Gtk
    class FileChooserWindow(Gtk.Window):
        def __init__(self):
            Gtk.Window.__init__(self, title="File Chooser Example")
            self.set_default_size(200, 100)
            box = Gtk.Box(spacing=6)
            self.add(box)
            button1 = Gtk.Button("Choose File")
            button1.connect("clicked", self.on_file_clicked)
            box.add(button1)
        def on_file_clicked(self, button):
            dialog = Gtk.FileChooserDialog("Please choose a file", self, Gtk.FileChooserAction.OPEN,
                                           (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                           Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
            response = dialog.run()
            if response == Gtk.ResponseType.OK:
                filename = dialog.get_filename()
                with open(filename, 'r') as file:
                    file_content = file.read()
                    print("File content: ", file_content)
            dialog.destroy()
    win = FileChooserWindow()
    win.connect("destroy", Gtk.main_quit)
    win.show_all()
    Gtk.main()
    

    这个示例中,当用户点击按钮选择文件后,会在终端输出文件的内容。你可以根据需求将文件内容显示到GUI的其他部分。

    评论

报告相同问题?