button1 = Gtk.Button("Choose File")
button1.connect("clicked", self.on_file_clicked)
box.add(button1)
self.on_file_clicked是一个可以打开文件的回调函数,但是现在我选择文件以后需要对文件显示出来,请问怎么做呢?
button1 = Gtk.Button("Choose File")
button1.connect("clicked", self.on_file_clicked)
box.add(button1)
self.on_file_clicked是一个可以打开文件的回调函数,但是现在我选择文件以后需要对文件显示出来,请问怎么做呢?
关注让阿豪来帮你解答,本回答参考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的其他部分。