Skip to main content
 首页 » 编程设计

python之如何在 Tkinter 中使用列表框打开文本文件

2024年11月01日10Free-Thinker

我正在使用适用于 Windows 的 Python 3.2 和 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”的定义,以便在选择列表中的项目时,打开链接到该项目的文本文件,并将其内容显示在文本小部件中。我需要知道如何将文件链接到列表框项目以及如何使用上面代码中显示的处理程序调用它。

请您参考如下方法:

文本文件

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

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 .与由一系列数字索引的数组或列表不同,字典由键索引,键可以是任何不可变类型;字符串和数字总是可以作为键。因此,例如,您可以将文件名作为键,将列表框中的任何内容作为值。

希望能帮到您。