python-2.7 - 是否可以通过在 Tkinter 中读取保存的文件来创建按钮
问题描述
我有一个按钮,可以将框架切换为可见或隐藏,并且框架内部包含一些按钮。
我有一个保存的文件,我将在其中存储我想显示的按钮的名称。
有什么可能的方法可以使用保存的文件来创建要显示的按钮(在多个文件的情况下)
目前我只能预先创建按钮
解决方案
因此,根据您所描述的内容和您提供的示例文本文件,这里是一个(不是最好的)适合您的工作解决方案。必须阅读代码片段中的注释才能理解我做了什么。
总而言之,只需读取文件,将数据保存在一个variable
(可能是list
,dict
或其他)中。然后使用这些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()
您提供的文本文件的程序示例图像::
推荐阅读
- flutter - When I try to build APK as the release version, I got a gray screen without nothing inside that in Flutter
- javascript - Reorganization and cleaning of a 'treeview' JSON object
- bloomberg - Can we use BLPAPI remotely?
- spring-boot - Azure active directory integration angular + adal+ spring boot
- r - R滚动连接两个data.tables,连接时有误差
- nginx - Nginx does not serve css and js from upstream servers
- reactjs - Firebase + react : read document in auth state changed and add it to context
- c++ - 类型特征是否可以限制为不接受其他类型特征作为参数?
- javascript - 添加动态按钮以显示弹出窗口以链接条目
- javascript - XMLHttpRequest() 在 Opera mini 中不起作用