繁体   English   中英

Python tkinter:创建动态下拉菜单,并在选择后调用不同的操作

[英]Python tkinter: create a dynamic dropdown menu and call different actions after selection

我对python很陌生,这是我第一次使用tkinter,所以我希望有人可以帮助我找到正确的方向。

基本上,这就是我想要实现的目标:

  1. 我从XML 2列表(APP,ID)中检索;
  2. APP列表将显示在下拉菜单中;
  3. 下拉菜单中的APP选择将使用其ID调用APP状态。

我无法处理最后一点,基本上我想我理解为什么(我在两个列表之间没有匹配项,或者没有一个匹配它们的函数,并且选择自动调用了第二个列表的最后一个ID),但是我做到了最好据我所知无法解决。

import requests
import xml.etree.ElementTree as ET

import tkinter as tk

APP_OPTIONS = []
ID_OPTIONS = []

session = requests.Session()
session.auth = ('USER', 'PW')
applications = session.get('https://getapplicationslist.myurl.com/application/')
applications_xml = applications.content
root = ET.fromstring(applications_xml)
for application in root.findall('application'):
    app_name = application.find('name').text
    app_id = application.find('id').text
    APP_OPTIONS.append(app_name)
    ID_OPTIONS.append(app_id)

def appcall(*args):
    app_status = session.get('https://getapplicationstatus.myurl.com?Id=' + app_id)
    status_xml = app_status.content
    root = ET.fromstring(status_xml)
    for appStatus in root.findall('appStatus'):
        status = appStatus.find('status').text
        print(status)

root = tk.Tk()
root.title('Application List')
root.geometry("300x200")

var =tk.StringVar(root)
var.set('Choose an Application')
var.trace('w', appcall)

dropDownMenu = tk.OptionMenu(root, var, *APP_OPTIONS)
dropDownMenu.pack()

root.mainloop()
print('End Request')

如我的评论中所述,问题是您在app_id中的appcall不会更改。 您需要改为从ID_OPTIONS获取相应的ID

def appcall(*args):
    app_id = ID_OPTIONS[APP_OPTIONS.index(var.get())]  # Add this line
    app_status = session.get('https://getapplicationstatus.myurl.com?Id=' + app_id)
    ...

所述app_id现在设置到ID_OPTIONS相同的索引的基础上, app_name (由于插入顺序是相同的)。

但是 ,更好的方法是将选项初始化为字典:

# instead of APP_OPTIONS / ID_OPTIONS, create:
apps = {}

...

for application in root.findall('application'):
    app_name = application.find('name').text
    app_id = application.find('id').text
    # add to dictionary here:
    apps[app_name] = app_id

def appcall(*args):
    # Change the app_id to apps.get(var.get())
    app_status = session.get('https://getapplicationstatus.myurl.com?Id=' + apps.get(var.get())
    ...

看看调用同一参考文献要简单多少?

如果您对语言感到满意,甚至可以选择词典理解:

...
root = ET.fromstring(applications_xml)
app_id = {application.find('name').text: application.find('id').text for application in root.findall('application')}
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM