[英]Python tkinter: create a dynamic dropdown menu and call different actions after selection
我對python很陌生,這是我第一次使用tkinter,所以我希望有人可以幫助我找到正確的方向。
基本上,這就是我想要實現的目標:
我無法處理最后一點,基本上我想我理解為什么(我在兩個列表之間沒有匹配項,或者沒有一個匹配它們的函數,並且選擇自動調用了第二個列表的最后一個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.