【问题标题】:How to open text files using a listbox in Tkinter如何在 Tkinter 中使用列表框打开文本文件
【发布时间】:2013-11-05 22:38:00
【问题描述】:

我正在使用 Python 3.2 for Windows 和 Tkinter 8.5。有谁知道是否可以通过选择列表框中的项目并在文本小部件上显示文本文件内容来打开文本文件?这是我的代码:

def starters_menu():
        self.listBox.delete(0, END)
        starters_menu = open("starters_menu.txt")
        for line in starters_menu:
            line = line.rstrip()
            self.listBox.insert(END, line)
        self.listBox.bind("<ButtonRelease-1>", recipe_title, add="+")
        self.listBox.bind("<ButtonRelease-1>", recipe_ingredients, add="+")
    recipe_menu.add_command(label="Starters, Snacks and Savouries", command=starters_menu)

我需要帮助来编写“recipe_ingredients”的定义,以便在选择列表中的项目时,会打开一个链接到该项目的文本文件,并将其内容显示在文本小部件中。我需要知道如何将文件链接到列表框项以及如何使用上面代码中显示的处理程序调用它。

【问题讨论】:

    标签: python tkinter listboxitems


    【解决方案1】:

    文本文件

    您可以打开一个文本文件并将其内容转储到一个字符串中,如下所示:

    textFile = open(filename, 'r')
    #open() returns a file object
    #'r' opens the file for reading. 'w' would be writing
    textString = textFile.read()
    #This takes the file object opened with the open() and turns it into a string which
    #you can now use textString in a text widget.
    

    More info on text files and Python

    链接列表框和文本文件

    要将列表框项与文本文件链接,我想您可以将列表框中的所有内容都放在字典more info here 中。与由一系列数字索引的数组或列表不同,字典由键索引,键可以是任何不可变类型;字符串和数字总是可以作为键。因此,例如,您可以将文件名作为键,将列表框中的任何内容作为值。

    我希望我能帮上一点忙。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 2021-02-03
      相关资源
      最近更新 更多