I'm trying to create a dropdown menu in HTML using info from a python script. I've gotten it to work thus far, however, the html dropdown displays all 4 values in the lists as 4 options.
Current: Option 1: Red, Blue, Black Orange; Option 2: Red, Blue, Black, Orange etc. (Screenshot in link) Current
Desired: Option 1: Red Option 2: Blue etc.
How do I make it so that the python list is separated?
dropdown.py
from flask import Flask, render_template, request app = Flask(__name__) app.debug = True @app.route('/', methods=['GET']) def dropdown(): colours = ['Red', 'Blue', 'Black', 'Orange'] return render_template('test.html', colours=colours) if __name__ == "__main__": app.run()
test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Dropdown</title> </head> <body> <select name= colours method="GET" action="/"> {% for colour in colours %} <option value= "{{colour}}" SELECTED>{{colours}}</option>" {% endfor %} </select> </body> </html>
Build A Paint Program With TKinter and Python In this case, we can use the Tkinter OptionMenu(win, menu_to_set, options) function. First, we will instantiate an object of StringVar(), then we will set the initial value of the dropdown menu.
You need to use {{colour}}
in both places (instead of {{colours}}
in the second place):
<select name="colour" method="GET" action="/"> {% for colour in colours %} <option value="{{colour}}" SELECTED>{{colour}}</option>" {% endfor %} </select>
Note that using selected
inside the loop will add selected
attribute to all options and the last one will be selected, what you need to do is the following:
<select name="colour" method="GET" action="/"> <option value="{{colours[0]}}" selected>{{colours[0]}}</option> {% for colour in colours[1:] %} <option value="{{colour}}">{{colour}}</option> {% endfor %} </select>
you have a typo, replace colours
to colour
<option value= "{{colour}}" SELECTED>{{colours}}</option>"
replace to
<option value= "{{colour}}" SELECTED>{{ colour }}</option>" <!-- ^^^^ -->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With