如何使用Tkin中的列表框打开文本文件

2024-09-28 03:25:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3.2forwindows和tkinter8.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)

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


Tags: 项目代码文本selfadd内容bind部件
1条回答
网友
1楼 · 发布于 2024-09-28 03:25:11

文本文件

可以打开文本文件并将其内容转储为如下字符串:

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

将列表框与文本文件链接

为了将listbox项与文本文件链接起来,我想您可以在字典的列表框中拥有所有要放入的内容more info here。与数组或列表不同的是,数组或列表是按一系列数字编制索引的,而键可以是任何不可变的类型;字符串和数字总是可以是键。例如,你可以用一个文件名作为键,在列表框中输入任何你想要的值。在

我希望我能帮点忙。在

相关问题 更多 >

    热门问题