首页 > 解决方案 > 是否可以通过在 Tkinter 中读取保存的文件来创建按钮

问题描述

我有一个按钮,可以将框架切换为可见或隐藏,并且框架内部包含一些按钮。

我有一个保存的文件,我将在其中存储我想显示的按钮的名称。

有什么可能的方法可以使用保存的文件来创建要显示的按钮(在多个文件的情况下)

目前我只能预先创建按钮

标签: python-2.7tkinter

解决方案


因此,根据您所描述的内容和您提供的示例文本文件,这里是一个(不是最好的)适合您的工作解决方案。必须阅读代码片段中的注释才能理解我做了什么。

总而言之,只需读取文件,将数据保存在一个variable(可能是listdict或其他)中。然后使用这些variables来创建widgets.

如果我错过了问题中的某个点或者我误解了问题,请告诉我。

try:
    import tkinter as tk  # for python 3.x
except ImportError:
    import Tkinter as tk  # for python 2.x

# a function to create buttons. Optional if you don't plan to
# give these buttons a command (I'm sure you will but it's up to you)
def createButton(buttonName):
    tk.Button(root, text=buttonName).pack()

# reading the file content
with open('test.txt') as file:
    buttonNames = file.read().split()
    
root = tk.Tk()
root.geometry('200x200')

# Looping through the names that were in the file
for buttonName in buttonNames:
    createButton(buttonName)

root.mainloop()

您提供的文本文件的程序示例图像::

altText=IMGUR 没有这样做


推荐阅读