python - 与生成一组按钮的函数分开读取标签
问题描述
我正在使用 Python 中的 Tkinter、ElementTree 和 Pandas 模块进行以下开发:
from tkinter import *
import xml.etree.ElementTree as ET
import pandas as pd
file_xml = ET.parse('example1.xml')
rootXML = file_xml.getroot()
root = Tk()
root.title("Graphical Analysis of Signals of a XML")
root.geometry("1024x820")
root.pack_propagate(False)
root.config(bd=15)
# Functions to open xml file
def open_file():
try:
global temxml, xml_Name
xml_Name = str(easygui.fileopenbox(title='Select xml file', default='*.xml'))
if str(os.path.abspath(xml_Name)) != os.path.join(os.path.abspath(os.getcwd()), os.path.basename(xml_Name)):
menssage.set("Opened xml file: ", xml_Name)
child_4_separate(os.path.basename(str(tempxml)))
else:
child_4_separate(os.path.basename(str(xml_Name)))
except FileNotFoundError:
print('XML file was not loaded.')
# Function to display buttons and choose the Child_4 to be plotted
def child_4_separate(xml_Name):
print("File: ", xml_Name)
file_xml = ET.parse(xml_Name)
data_xml = [
{
"Name": signal.attrib["Name"],
"Id": signal.attrib["Id"],
} for signal in file_xml.findall(".//Child_4")
]
# print(data_xml)
for i in data_xml:
print(i)
id_tc = i.get('Id')
dict_tc = str(i.values()).replace('dict_values([\'', '')
name_tc = dict_tc.replace('\'])', '')
Button(root, text=f"TC> {name_tc}", command=transfor_data_atri_child_4(xml_Name, id_tc)).pack()
# Function to transform xml file to DataFrame
def transfor_data_atri_child_4(rootXML, id_tc):
print("File: ", rootXML)
print("id_tc: ", id_tc)
我想要做的是,每次我单击一个按钮时,child_4_separate (xml_Name)
它都会使用一个 ID 号转到该transform_data_atri_child_4 (rootXML, id_tc)
函数,并且不会像我在下面显示的最后一个打印中那样获取我的所有内容,这是能够分别操纵它们。
我在此链接example1.xml中共享 XML 文件,因为它有多长。
我不知道我是否需要另一个 for inside 或我需要什么,因为当在child_4_separate (xml_Name)
函数中已经存在的 for 中尝试另一个 for 时,它会重复很多次,这不是我想要的,而只是重定向到以下使用我所指示的两个参数来运行,但要分开;请帮帮我!预先,非常感谢您!
解决方案
只是为了以后可能的搜索或相关问题,我分享解决方案:
取command = lambda x = xml_Name, y = id_tc: transform_data_atri_child_4 (x, y)
按钮属性中的值,它起作用了,我的功能是这样的:
# Function to display buttons and choose the Child_4 to be plotted
def child_4_separate(xml_Name):
# print("File: ", xml_Name)
file_xml = ET.parse(xml_Name)
data_xml = [
{
"Name": signal.attrib["Name"],
"Id": signal.attrib["Id"],
} for signal in file_xml.findall(".//Child_4")
]
# print(data_xml)
for i in data_xml:
id_tc = i.get('Id')
dict_tc = str(i.values()).replace('dict_values([\'', '')
name_tc = dict_tc.replace('\'])', '')
Button(root, text=f"TC> {name_tc}", command=lambda x=xml_Name, y=id_tc: transfor_data_atri_child_4(x, y)).pack()
我很欣赏@Sujay 的解决方案。祝大家编纂快乐!!
推荐阅读
- testing - 在异步测试中重用昂贵的运行时生成的值
- docker - 如何在 docker-compose 容器中设置用户 ID
- amazon-web-services - 服务:AmazonCloudFront;状态码:409;错误代码:CNAMEAlreadyExists;
- tensorflow - ML.NET - 如何创建一个新的/空的 TensorFlow 模型
- shell - 我应该在这个反向外壳中放入什么?
- ruby-on-rails - ShopifySessionRepository.shop_storage 未配置
- php - 结帐/购物篮系统的 PHP 会话变量
- c - 加上字母表
- python - 问:在 Kivy 中替代 Clock.schedule_interval
- google-cloud-storage - 在 GCS 存储桶 python 仍在写入时获取所有项目